Error[8]: Undefined offset: 2317, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

3.寻找重复数字

public boolean findRepeatNum(int[] nums){
	HashSet<Integer> set = new HashSet();
	for (Integer i : nums){
		if(set.contains(i)){
			return true;
		}else{
			set.add(i);
		}
	}
	return false;
}

4.查找二维数组中的值

public boolean findNumInTrix(int[][] nums,int num){
	int i = 0,int j = nums[0].length;
	while (i<=nums.length&&j>=0){
		if(num < nums[i][j]){
			j--;
		}else if(num> nums[i][j]) {
			i++
		}else{
			return true;
		}
	}
	return false;
}

5.替换空格

public String replaceWhiteSpace(){
	StringBuilder sb = new StringBuilder();
	for (Character c:sb.toCharArray()){
		if (c==' '){
			sb.append("20%")
		}
		sb.append(c);
	}
	return sb.toString();
}

6.反向打印链表
方法一:辅助栈法

Stack<Integer> stack = new Stack();
public void reverseListNode(ListNode head){
	while(head!= null){
		stack.push(head.val);
		head = head.next;
	}
}

public void print(){
	while (stack.size()!=0){
		System.out.println(stack.pop);
	}
}

方法二:递归法

LinkedList<Integer> list = new LinkedList();
public void printListNode(ListNode head){
	recur(head);
	for(int i = 0;i<list.lenth;i++){
		System.out.println(list.get(i));
	}
}
//递归将数字装入list
public void recur(ListNode head){
	if(head == null){
	return;
	}
	recur(head.next);
	list.add(head.val);
}

7.重建二叉树-是一个不断寻找左右子树的过程

  1. 制作中序遍历的下标集合
  2. 递归方法
  3. 边界判断

class Solution {
    int[] preorder;
    HashMap<Integer, Integer> dic = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        for(int i = 0; i < inorder.length; i++)
            dic.put(inorder[i], i);
        return recur(0, 0, inorder.length - 1);
    }
    //root:先序遍历的索引;left:中序遍历左边界;right:中序遍历右边界
    TreeNode recur(int root, int left, int right) {
        if(left > right) return null;                          // 递归终止
        TreeNode node = new TreeNode(preorder[root]);          // 建立根节点
        //中序遍历索引根索引
        int i = dic.get(preorder[root]);                       // 划分根节点、左子树、右子树
        node.left = recur(root + 1, left, i - 1);              // 开启左子树递归
        node.right = recur(root + i - left + 1, i + 1, right); // 开启右子树递归
        return node;                                           // 回溯返回根节点
    }
}

8.两个栈实现队列

class soluation{
	private Stack<Integer> stackIn;
	private Stack<Integer> stackOUt;
	public Queue(){
		stackIn = new Stack<Integer>;
		stackOut = new Stack<Integer>;
	}
	public void queueIn(Integer i){
		stackIn.add(i);
	}

	public Integer queueOut(){
		if(stackOut.size()!=0){
			return stackOut.pop();
		}
		if(stackIn.size()==0){
			return null;
		}
		while (stackIn.size!=0){
			stackOut.push(stackIn.pop);
		}
		return stackOut.pop;
	}
}

10.斐波那契数列

public Integer fib(Integer num){
	int fib0=0;
	int fib1=1;
	int tmp = 0;
	for(int i=0 ; i<num ; i++){
		tmp = (fib0 + fib1)%1000000007;
		fib0 = fib1;
		fib1 = tmp;
	}
	return fib1;
}

11.旋转数组的最小数字-二分法

public Integer findMinNum(int[] nums){
	int i =0,j=nums.length;
	int m = (i+j)/2;
	while (i<j){
		if(nums[m]<nums[j]){
			j = m;
		}else if(nums[m]>[j]){
			i==m+1;
		}else{
			j--;
		}
	}
	retrun nums[i];
}

13.矩阵中的路径

public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(dfs(board, words, i, j, 0)) return true;
            }
        }
        return false;
    }
    boolean dfs(char[][] board, char[] word, int i, int j, int k) {
        if(i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k]) return false;
        if(k == word.length - 1) return true;
        board[i][j] = ';'boolean
        = res dfs (,board, word+ i 1 ,, j+ k 1 )|| dfs (,board, word- i 1 ,, j+ k 1 )|| dfs 
                      (,board, word, i+ j 1 ,+ k 1 )|| dfs (,board, word, i - j 1 ,+ k 1 );[
        board]i[]j= [ word]k;return
        ; res}
    public

14.剪绳子
核心思想:3最优,2次优,1最差

int cuttingRope (int) nif {
        (<n3)return ; n=
        x % n3;=
        y / n3;if
        (==x0). reutrn Mathpow(3,)y;if
        (==x2)return . Mathpow(3,-y1)*2;if
        (==x1)return . Mathpow()}
    public

15.二进制中“1”的个数

class Solution // you need to treat n as an unsigned value {
    public
    int hammingWeight (int) nint {
        = res 0 ;while
        ( !=n0 )+={
            res & n1;1
            n>>>=;}
        return
        ; res}
    }
public

16.数值的整数次方
核心思想:就是一个降幂的过程。x是底数,n是指数,ans是结果,x^n代表的是一个数值,快速幂说白了就是在确保数值不变的情况下,用二分法把数值从指数不断地往底数里面搬。核心是n=n/2, x=x^2这两句代码。但是由于指数可能是奇数,整数除二会丢失一位底数,所以要在ans里面记录奇数轮丢失的底数。

double myPow (double, xint ) nif {
        (==x 0 )return 0 ;long
        = b ; ndouble
        = res 1.0 ;if
        (<b 0 )= {
            x 1 / ; x=
            b - ;b}
        while
        (0b > )if {
            ((&b 1 )== 1 )*= res ; x*=
            x ; x1
            b >>= ;}
        return
        ; res}
    public

17.打印从1到n的最大n位数

 int []printNumbers (int) nint {
        = end ( int).Mathpow(10,) n- 1 ;int
        []= res new int []end;for
        (int= i 0 ;< i ; end++ i)[
            res]i= + i 1 ;return
        ; res}
    public

18.删除链表的节点

deleteNode ListNode (,ListNode headint ) valif {
        
        ( .head==val ) valreturn . head;next=
        ListNode pre,head=cur.head;nextwhile
        (!=cur&&null . cur!=val)val={
            pre ; cur=
            cur . cur;next}
        .
        pre=next . cur;nextreturn
        ; head}
    class

19.正则表达式匹配

Solution public {
    boolean isMatch (,String s) String pint {
        = m . slength()+ 1 ,= n . plength()+ 1 ;boolean
        [][]= dp new boolean []m[]n;[
        dp0][0]= true ;for
        (int= j 2 ;< j ; n+= j 2 )[
            dp0][]j= [ dp0][-j 2 ]&& . pcharAt(-j 1 )== '*' ;for
        (int= i 1 ;< i ; m++ i)for {
            (int= j 1 ;< j ; n++ j)[ {
                dp]i[]j= . pcharAt(-j 1 )== '*' ? [
                    dp]i[-j 2 ]|| [ dp-i 1 ][]j&& ( .scharAt(-i 1 )== . pcharAt(-j 2 )|| . pcharAt(-j 2 )== '.' ): [
                    dp-i 1 ][-j 1 ]&& ( .pcharAt(-j 1 )== '.' || . scharAt(-i 1 )== . pcharAt(-j 1 ));}
            }
        return
        [ dp-m 1 ][-n 1 ];}
    }
class

20.表示数值的字符串(有限状态机)

Solution public {
    boolean isNumber ()String s[ {
        Map]= states new {
            HashMap <(>)put {{ (' ',0 );put ('s',1 );put ('d',2 );put ('.',4 );} },// 0. new
            HashMap <(>)put {{ ('d',2 );put ('.',4 );} },// 1.                           new
            HashMap <(>)put {{ ('d',2 );put ('.',3 );put ('e',5 );put (' ',8 );} },// 2. new
            HashMap <(>)put {{ ('d',3 );put ('e',5 );put (' ',8 );} },// 3.              new
            HashMap <(>)put {{ ('d',3 );} },// 4.                                        new
            HashMap <(>)put {{ ('s',6 );put ('d',7 );} },// 5.                           new
            HashMap <(>)put {{ ('d',7 );} },// 6.                                        new
            HashMap <(>)put {{ ('d',7 );put (' ',8 );} },// 7.                           new
            HashMap <(>)put {{ (' ',8 );} }// 8.                                         }
        ;int
        = p 0 ;char
        ; tfor
        (char: c . stoCharArray())if {
            ('0'c >= && <= c '9' )= t 'd' ;else
            if (==c '+' || == c '-' )= t 's' ;else
            if (==c 'e' || == c 'E' )= t 'e' ;else
            if (==c '.' || == c ' ' )= t ; celse
            = t '?' ;if
            (![states]p.containsKey()t)return false ;=
            p ( int)[states]p.get()t;}
        return
        == p 2 || == p 3 || == p 7 || == p 8 ;}
    }
class

21.调换数组顺序是奇数位于偶数之前


Solution public {
    int []exchange (int[]) numsint {
        = i 0 ,= j . nums-length 1 ,; tmpwhile
        (<i ) jwhile {
            (<i && j ( [nums]i& 1 )== 1 )++ i;while
            (<i && j ( [nums]j& 1 )== 0 )-- j;=
            tmp [ nums]i;[
            nums]i= [ nums]j;[
            nums]j= ; tmp}
        return
        ; nums}
    }
class

22.链表中倒数第k个值

Solution public {
    getKthFromEnd ListNode (,ListNode headint ) k= {
        ListNode former , head= latter ; headfor
        (int= i 0 ;< i ; k++ i)=
            former . former;nextwhile
        (!=former ) null= {
            former . former;next=
            latter . latter;next}
        return
        ; latter}
    }
class

24.反转链表
方法一:迭代(双指针)

Solution public {
    reverseList ListNode ()ListNode head= {
        ListNode cur , head= pre ; nullwhile
        (!=cur ) null= {
            ListNode tmp . cur;next// 暂存后继节点 cur.next .
            cur=next ; pre// 修改 next 引用指向          =
            pre ; cur// pre 暂存 cur               =
            cur ; tmp// cur 访问下一节点               }
        return
        ; pre}
    }
class

方法二:递归


Solution public {
    reverseList ListNode ()ListNode headreturn {
        recur (,head) null;// 调用递归并返回    }
    private
    recur ListNode (,ListNode cur) ListNode preif {
        ( ==cur ) nullreturn ; pre// 终止条件 =
        ListNode res recur (.cur,next) cur;// 递归后继节点  .
        cur=next ; pre// 修改节点引用指向              return
        ; res// 返回反转链表的头节点                  }
    }
class

25.合并两个排序链表

Solution public {
    mergeTwoLists ListNode (,ListNode l1) ListNode l2= {
        ListNode dum new ListNode (0),= cur ; dumwhile
        (!=l1 && null != l2 ) nullif {
            (.l1<val . l2)val. {
                cur=next ; l1=
                l1 . l1;next}
            else
            . {
                cur=next ; l2=
                l2 . l2;next}
            =
            cur . cur;next}
        .
        cur=next != l1 ? null : l1 ; l2return
        . dum;next}
    }
class

26.树的子结构

Solution public {
    boolean isSubStructure (,TreeNode A) TreeNode Breturn {
        ( !=A && null != B ) null&& ( recur(,A) B|| isSubStructure (.A,left) B|| isSubStructure (.A,right) B);}
    boolean
    recur (,TreeNode A) TreeNode Bif {
        (==B ) nullreturn true ;if
        (==A || null . A!=val . B)valreturn false ;return
        recur (.A,left. B)left&& recur (.A,right. B)right;}
    }
class

27.二叉树的镜像
方法一:递归

Solution public {
    mirrorTree TreeNode ()TreeNode rootif {
        (==root ) nullreturn ; null=
        TreeNode tmp . root;left.
        root=left mirrorTree (.root)right;.
        root=right mirrorTree ()tmp;return
        ; root}
    }
class

方法二:辅助栈

Solution public {
    mirrorTree TreeNode ()TreeNode rootif {
        (==root ) nullreturn ; null<
        Stack=TreeNode> stack new Stack <(>)add {{ ()root;} };while
        (!.stackisEmpty())= {
            TreeNode node . stackpop();if
            (.node!=left ) null. stackadd(.node)left;if
            (.node!=right ) null. stackadd(.node)right;=
            TreeNode tmp . node;left.
            node=left . node;right.
            node=right ; tmp}
        return
        ; root}
    }
class

28.对称的二叉树


Solution public {
    boolean isSymmetric ()TreeNode rootreturn {
        == root ? null true : recur (.root,left. root)right;}
    boolean
    recur (,TreeNode L) TreeNode Rif {
        (==L && null == R ) nullreturn true ;if
        (==L || null == R || null . L!=val . R)valreturn false ;return
        recur (.L,left. R)right&& recur (.L,right. R)left;}
    }
class

29.顺时针打印矩阵


Solution public {
    int []spiralOrder (int[][]) matrixif {
        (.matrix==length 0 )return new int [0];int
        = l 0 ,= r [ matrix0].-length 1 ,= t 0 ,= b . matrix-length 1 ,= x 0 ;int
        []= res new int [(+r 1 )* ( +b 1 )];while
        (true)for {
            (int= i ; l<= i ; r++ i)[ res++x]= [ matrix]t[]i;// left to right. if
            (++)t > bbreak ;for
            (int= i ; t<= i ; b++ i)[ res++x]= [ matrix]i[]r;// top to bottom. if
            (--l > )rbreak ;for
            (int= i ; r; i >= l-- i)[ res++x]= [ matrix]b[]i;// right to left. if
            (--t > )bbreak ;for
            (int= i ; b; i >= t-- i)[ res++x]= [ matrix]i[]l;// bottom to top. if
            (++)l > rbreak ;}
        return
        ; res}
    }
class

30.包含main函数的栈

MinStack < {
    Stack,Integer> A; Bpublic
    MinStack ()= {
        A new Stack <(>);=
        B new Stack <(>);}
    public
    void push (int) x. {
        Aadd()x;if
        (.Bempty()|| . Bpeek()) >= x.
            Badd()x;}
    public
    void pop ()if {
        (.Apop().equals(.Bpeek())).
            Bpop();}
    public
    int top ()return {
        . Apeek();}
    public
    int min ()return {
        . Bpeek();}
    }
[+++]

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 165, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
剑指Offer刷题笔记_java_内存溢出

剑指Offer刷题笔记

剑指Offer刷题笔记,第1张

3.寻找重复数字

public boolean findRepeatNum(int[] nums){
	HashSet<Integer> set = new HashSet();
	for (Integer i : nums){
		if(set.contains(i)){
			return true;
		}else{
			set.add(i);
		}
	}
	return false;
}

4.查找二维数组中的值

public boolean findNumInTrix(int[][] nums,int num){
	int i = 0,int j = nums[0].length;
	while (i<=nums.length&&j>=0){
		if(num < nums[i][j]){
			j--;
		}else if(num> nums[i][j]) {
			i++
		}else{
			return true;
		}
	}
	return false;
}

5.替换空格

public String replaceWhiteSpace(){
	StringBuilder sb = new StringBuilder();
	for (Character c:sb.toCharArray()){
		if (c==' '){
			sb.append("20%")
		}
		sb.append(c);
	}
	return sb.toString();
}

6.反向打印链表
方法一:辅助栈法

  • 这种方法真的非常巧妙,后加入的节点后交换位置,完美的诠释了栈的作用;
Stack<Integer> stack = new Stack();
public void reverseListNode(ListNode head){
	while(head!= null){
		stack.push(head.val);
		head = head.next;
	}
}

public void print(){
	while (stack.size()!=0){
		System.out.println(stack.pop);
	}
}

方法二:递归法

LinkedList<Integer> list = new LinkedList();
public void printListNode(ListNode head){
	recur(head);
	for(int i = 0;i<list.lenth;i++){
		System.out.println(list.get(i));
	}
}
//递归将数字装入list
public void recur(ListNode head){
	if(head == null){
	return;
	}
	recur(head.next);
	list.add(head.val);
}

7.重建二叉树-是一个不断寻找左右子树的过程

  1. 制作中序遍历的下标集合
  2. 递归方法
  3. 边界判断

class Solution {
    int[] preorder;
    HashMap<Integer, Integer> dic = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        for(int i = 0; i < inorder.length; i++)
            dic.put(inorder[i], i);
        return recur(0, 0, inorder.length - 1);
    }
    //root:先序遍历的索引;left:中序遍历左边界;right:中序遍历右边界
    TreeNode recur(int root, int left, int right) {
        if(left > right) return null;                          // 递归终止
        TreeNode node = new TreeNode(preorder[root]);          // 建立根节点
        //中序遍历索引根索引
        int i = dic.get(preorder[root]);                       // 划分根节点、左子树、右子树
        node.left = recur(root + 1, left, i - 1);              // 开启左子树递归
        node.right = recur(root + i - left + 1, i + 1, right); // 开启右子树递归
        return node;                                           // 回溯返回根节点
    }
}

8.两个栈实现队列

class soluation{
	private Stack<Integer> stackIn;
	private Stack<Integer> stackOUt;
	public Queue(){
		stackIn = new Stack<Integer>;
		stackOut = new Stack<Integer>;
	}
	public void queueIn(Integer i){
		stackIn.add(i);
	}

	public Integer queueOut(){
		if(stackOut.size()!=0){
			return stackOut.pop();
		}
		if(stackIn.size()==0){
			return null;
		}
		while (stackIn.size!=0){
			stackOut.push(stackIn.pop);
		}
		return stackOut.pop;
	}
}

10.斐波那契数列

public Integer fib(Integer num){
	int fib0=0;
	int fib1=1;
	int tmp = 0;
	for(int i=0 ; i<num ; i++){
		tmp = (fib0 + fib1)%1000000007;
		fib0 = fib1;
		fib1 = tmp;
	}
	return fib1;
}

11.旋转数组的最小数字-二分法

public Integer findMinNum(int[] nums){
	int i =0,j=nums.length;
	int m = (i+j)/2;
	while (i<j){
		if(nums[m]<nums[j]){
			j = m;
		}else if(nums[m]>[j]){
			i==m+1;
		}else{
			j--;
		}
	}
	retrun nums[i];
}

13.矩阵中的路径

public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(dfs(board, words, i, j, 0)) return true;
            }
        }
        return false;
    }
    boolean dfs(char[][] board, char[] word, int i, int j, int k) {
        if(i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k]) return false;
        if(k == word.length - 1) return true;
        board[i][j] = ';'boolean
        = res dfs (,board, word+ i 1 ,, j+ k 1 )|| dfs (,board, word- i 1 ,, j+ k 1 )|| dfs 
                      (,board, word, i+ j 1 ,+ k 1 )|| dfs (,board, word, i - j 1 ,+ k 1 );[
        board]i[]j= [ word]k;return
        ; res}
    public

14.剪绳子
核心思想:3最优,2次优,1最差

int cuttingRope (int) nif {
        (<n3)return ; n=
        x % n3;=
        y / n3;if
        (==x0). reutrn Mathpow(3,)y;if
        (==x2)return . Mathpow(3,-y1)*2;if
        (==x1)return . Mathpow()}
    public

15.二进制中“1”的个数

class Solution // you need to treat n as an unsigned value {
    public
    int hammingWeight (int) nint {
        = res 0 ;while
        ( !=n0 )+={
            res & n1;1
            n>>>=;}
        return
        ; res}
    }
public

16.数值的整数次方
核心思想:就是一个降幂的过程。x是底数,n是指数,ans是结果,x^n代表的是一个数值,快速幂说白了就是在确保数值不变的情况下,用二分法把数值从指数不断地往底数里面搬。核心是n=n/2, x=x^2这两句代码。但是由于指数可能是奇数,整数除二会丢失一位底数,所以要在ans里面记录奇数轮丢失的底数。

double myPow (double, xint ) nif {
        (==x 0 )return 0 ;long
        = b ; ndouble
        = res 1.0 ;if
        (<b 0 )= {
            x 1 / ; x=
            b - ;b}
        while
        (0b > )if {
            ((&b 1 )== 1 )*= res ; x*=
            x ; x1
            b >>= ;}
        return
        ; res}
    public

17.打印从1到n的最大n位数

 int []printNumbers (int) nint {
        = end ( int).Mathpow(10,) n- 1 ;int
        []= res new int []end;for
        (int= i 0 ;< i ; end++ i)[
            res]i= + i 1 ;return
        ; res}
    public

18.删除链表的节点

deleteNode ListNode (,ListNode headint ) valif {
        
        ( .head==val ) valreturn . head;next=
        ListNode pre,head=cur.head;nextwhile
        (!=cur&&null . cur!=val)val={
            pre ; cur=
            cur . cur;next}
        .
        pre=next . cur;nextreturn
        ; head}
    class

19.正则表达式匹配

Solution public {
    boolean isMatch (,String s) String pint {
        = m . slength()+ 1 ,= n . plength()+ 1 ;boolean
        [][]= dp new boolean []m[]n;[
        dp0][0]= true ;for
        (int= j 2 ;< j ; n+= j 2 )[
            dp0][]j= [ dp0][-j 2 ]&& . pcharAt(-j 1 )== '*' ;for
        (int= i 1 ;< i ; m++ i)for {
            (int= j 1 ;< j ; n++ j)[ {
                dp]i[]j= . pcharAt(-j 1 )== '*' ? [
                    dp]i[-j 2 ]|| [ dp-i 1 ][]j&& ( .scharAt(-i 1 )== . pcharAt(-j 2 )|| . pcharAt(-j 2 )== '.' ): [
                    dp-i 1 ][-j 1 ]&& ( .pcharAt(-j 1 )== '.' || . scharAt(-i 1 )== . pcharAt(-j 1 ));}
            }
        return
        [ dp-m 1 ][-n 1 ];}
    }
class

20.表示数值的字符串(有限状态机)

Solution public {
    boolean isNumber ()String s[ {
        Map]= states new {
            HashMap <(>)put {{ (' ',0 );put ('s',1 );put ('d',2 );put ('.',4 );} },// 0. new
            HashMap <(>)put {{ ('d',2 );put ('.',4 );} },// 1.                           new
            HashMap <(>)put {{ ('d',2 );put ('.',3 );put ('e',5 );put (' ',8 );} },// 2. new
            HashMap <(>)put {{ ('d',3 );put ('e',5 );put (' ',8 );} },// 3.              new
            HashMap <(>)put {{ ('d',3 );} },// 4.                                        new
            HashMap <(>)put {{ ('s',6 );put ('d',7 );} },// 5.                           new
            HashMap <(>)put {{ ('d',7 );} },// 6.                                        new
            HashMap <(>)put {{ ('d',7 );put (' ',8 );} },// 7.                           new
            HashMap <(>)put {{ (' ',8 );} }// 8.                                         }
        ;int
        = p 0 ;char
        ; tfor
        (char: c . stoCharArray())if {
            ('0'c >= && <= c '9' )= t 'd' ;else
            if (==c '+' || == c '-' )= t 's' ;else
            if (==c 'e' || == c 'E' )= t 'e' ;else
            if (==c '.' || == c ' ' )= t ; celse
            = t '?' ;if
            (![states]p.containsKey()t)return false ;=
            p ( int)[states]p.get()t;}
        return
        == p 2 || == p 3 || == p 7 || == p 8 ;}
    }
class

21.调换数组顺序是奇数位于偶数之前


Solution public {
    int []exchange (int[]) numsint {
        = i 0 ,= j . nums-length 1 ,; tmpwhile
        (<i ) jwhile {
            (<i && j ( [nums]i& 1 )== 1 )++ i;while
            (<i && j ( [nums]j& 1 )== 0 )-- j;=
            tmp [ nums]i;[
            nums]i= [ nums]j;[
            nums]j= ; tmp}
        return
        ; nums}
    }
class

22.链表中倒数第k个值

Solution public {
    getKthFromEnd ListNode (,ListNode headint ) k= {
        ListNode former , head= latter ; headfor
        (int= i 0 ;< i ; k++ i)=
            former . former;nextwhile
        (!=former ) null= {
            former . former;next=
            latter . latter;next}
        return
        ; latter}
    }
class

24.反转链表
方法一:迭代(双指针)

Solution public {
    reverseList ListNode ()ListNode head= {
        ListNode cur , head= pre ; nullwhile
        (!=cur ) null= {
            ListNode tmp . cur;next// 暂存后继节点 cur.next .
            cur=next ; pre// 修改 next 引用指向          =
            pre ; cur// pre 暂存 cur               =
            cur ; tmp// cur 访问下一节点               }
        return
        ; pre}
    }
class

方法二:递归


Solution public {
    reverseList ListNode ()ListNode headreturn {
        recur (,head) null;// 调用递归并返回    }
    private
    recur ListNode (,ListNode cur) ListNode preif {
        ( ==cur ) nullreturn ; pre// 终止条件 =
        ListNode res recur (.cur,next) cur;// 递归后继节点  .
        cur=next ; pre// 修改节点引用指向              return
        ; res// 返回反转链表的头节点                  }
    }
class

25.合并两个排序链表

Solution public {
    mergeTwoLists ListNode (,ListNode l1) ListNode l2= {
        ListNode dum new ListNode (0),= cur ; dumwhile
        (!=l1 && null != l2 ) nullif {
            (.l1<val . l2)val. {
                cur=next ; l1=
                l1 . l1;next}
            else
            . {
                cur=next ; l2=
                l2 . l2;next}
            =
            cur . cur;next}
        .
        cur=next != l1 ? null : l1 ; l2return
        . dum;next}
    }
class

26.树的子结构

Solution public {
    boolean isSubStructure (,TreeNode A) TreeNode Breturn {
        ( !=A && null != B ) null&& ( recur(,A) B|| isSubStructure (.A,left) B|| isSubStructure (.A,right) B);}
    boolean
    recur (,TreeNode A) TreeNode Bif {
        (==B ) nullreturn true ;if
        (==A || null . A!=val . B)valreturn false ;return
        recur (.A,left. B)left&& recur (.A,right. B)right;}
    }
class

27.二叉树的镜像
方法一:递归

Solution public {
    mirrorTree TreeNode ()TreeNode rootif {
        (==root ) nullreturn ; null=
        TreeNode tmp . root;left.
        root=left mirrorTree (.root)right;.
        root=right mirrorTree ()tmp;return
        ; root}
    }
class

方法二:辅助栈

Solution public {
    mirrorTree TreeNode ()TreeNode rootif {
        (==root ) nullreturn ; null<
        Stack=TreeNode> stack new Stack <(>)add {{ ()root;} };while
        (!.stackisEmpty())= {
            TreeNode node . stackpop();if
            (.node!=left ) null. stackadd(.node)left;if
            (.node!=right ) null. stackadd(.node)right;=
            TreeNode tmp . node;left.
            node=left . node;right.
            node=right ; tmp}
        return
        ; root}
    }
class

28.对称的二叉树


Solution public {
    boolean isSymmetric ()TreeNode rootreturn {
        == root ? null true : recur (.root,left. root)right;}
    boolean
    recur (,TreeNode L) TreeNode Rif {
        (==L && null == R ) nullreturn true ;if
        (==L || null == R || null . L!=val . R)valreturn false ;return
        recur (.L,left. R)right&& recur (.L,right. R)left;}
    }
class

29.顺时针打印矩阵


Solution public {
    int []spiralOrder (int[][]) matrixif {
        (.matrix==length 0 )return new int [0];int
        = l 0 ,= r [ matrix0].-length 1 ,= t 0 ,= b . matrix-length 1 ,= x 0 ;int
        []= res new int [(+r 1 )* ( +b 1 )];while
        (true)for {
            (int= i ; l<= i ; r++ i)[ res++x]= [ matrix]t[]i;// left to right. if
            (++)t > bbreak ;for
            (int= i ; t<= i ; b++ i)[ res++x]= [ matrix]i[]r;// top to bottom. if
            (--l > )rbreak ;for
            (int= i ; r; i >= l-- i)[ res++x]= [ matrix]b[]i;// right to left. if
            (--t > )bbreak ;for
            (int= i ; b; i >= t-- i)[ res++x]= [ matrix]i[]l;// bottom to top. if
            (++)l > rbreak ;}
        return
        ; res}
    }
class

30.包含main函数的栈

MinStack < {
    Stack,Integer> A; Bpublic
    MinStack ()= {
        A new Stack <(>);=
        B new Stack <(>);}
    public
    void push (int) x. {
        Aadd()x;if
        (.Bempty()|| . Bpeek()) >= x.
            Badd()x;}
    public
    void pop ()if {
        (.Apop().equals(.Bpeek())).
            Bpop();}
    public
    int top ()return {
        . Apeek();}
    public
    int min ()return {
        . Bpeek();}
    }


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/788268.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存