大小写敏感
类名class 首字母应该大写
方法名void 小写字母开头,后面的每个单词首字母大写f
源文件名和public类名相同 .java
所有的 Java 程序由 public static void main(String[] args) 方法开始执行
ADT
存
取
队列
offer(Obj)
poll()
栈
push(Obj)
pop()
集合
add(ele)
get(index)
ava自带的类
String integer.toBinaryString(int十进制)
返回二进制字符串;
翻译 intenger 转换器,tobinary二进制
int Integer.parseInt(string字符串,int指定字符串的进制)
返回十进制
正则表达式,java具体的实现没看
过完一遍java基础
1. Binary Search
1 2 3 4 5 6 7 8 9 10 start=0 ;end=len-1 ; while (start+1 <end){ mid=start+(end-start)/2 ; if (num[mid]<target) start=mid; else end=mid; }
用这个 //折半查找,如果数组不包含,不需要判断两头情况
1 2 3 4 5 6 7 8 9 start=0 ;end=length-1 ; while (start<=end){ mid=start+(end-start)/2 ; if (num[mid]<target) start=mid+1 ; else end=mid-1 ; }
1 2 3 4 5 6 7 8 9 10 11 static int binarysearch (int [] nums, int target) { int left = 0 , right = nums.length - 1 ; while (left <= right){ int mid = left+(right-left)/2 ; if (nums[mid] == target) return mid; else if (nums[mid]<target) left=mid+1 ; else right=mid-1 ; } return -1 ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Solution extends VersionControl { public int firstBadVersion (int n) { int left=1 ,right=n; while (left<=right){ int mid = left+(right-left)/2 ; if (!isBadVersion(mid)) left=mid+1 ; else right=mid-1 ; } return left; } }
410. 分割数组的最大值 Split Array Largest Sum二分猜答案1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 import java.util.Arrays;class Solution { public int splitArray (int [] nums, int m) { int sum = Arrays.stream(nums).sum(); int max = Arrays.stream(nums).max().getAsInt(); return binary(nums,m,sum,max); } private int binary (int [] nums,int m,int high,int low) { int mid = 0 ; while (low<=high){ mid=low+(high-low)/2 ; if (valid(nums,m,mid))high=mid-1 ; else low=mid+1 ; } return low; } private boolean valid (int [] nums, int m,int subArraySum) { int curSum = 0 ,count=1 ; for (int num:nums){ curSum +=num; if (curSum>subArraySum){ curSum=num; count++; if (count>m) return false ; } } return true ; } }
300.Longest increasing Subsequence最长递增子序列 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public int lengthOfLIS (int [] nums) { List<Integer> sub = new ArrayList <>(); sub.add(nums[0 ]); for (int i=1 ;i<nums.length;i++){ int num = nums[i]; if (num>sub.get(sub.size()-1 )) sub.add(num); else { int j=binarySearch(sub,num); sub.set(j,num); } }return sub.size(); } private int binarySearch (List<Integer> list, int target) { int left=0 ,right=list.size()-1 ; while (left <= right){ int mid=left+(right-left)/2 ; if (list.get(mid)==target)return mid; else if (list.get(mid)<target)left=mid+1 ; else right=mid-1 ; }return left; }
1 2 3 4 5 6 7 8 9 10 11 12 class Solution { public int minArray (int [] numbers) { int left=0 ,right=numbers.length-1 ; while (left<=right){ int mid=left+(right-left)/2 ; if (numbers[right]<numbers[mid])left=mid+1 ; else if (numbers[right]<numbers[mid])right=mid-1 ; else right--; } return numbers[left]; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution { public int search (int [] nums, int target) { int left=0 ,right=nums.length-1 ; while (left<=right){ int mid = left+(right-left)/2 ; if (nums[mid]==target)return mid; else if (nums[left]<=nums[mid]){ if (nums[mid]>target&&nums[left]<=target)right=mid-1 ; else left=mid+1 ; }else { if (nums[mid]<target&&nums[right]>=target)left=mid+1 ; else right=mid-1 ; } }return -1 ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 class Solution { public int mySqrt (int x) { int left = 1 , right = (x>>1 )+1 ; while (left<=right){ int mid=left+(right-left)/2 ; if (mid==x/mid) return mid; if (mid<x/mid) left=mid+1 ; else right = mid -1 ; } return right; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution { public int search (int [] nums, int target) { return help(nums,target)-help(nums,target-1 ); } private int help (int [] nums,int x) { int left = 0 ,right=nums.length-1 ; while (left<=right){ int mid=left+(right-left)/2 ; if (nums[mid]<=x)left=mid+1 ; else right=mid-1 ; } return left; } }
1 2 3 4 5 6 7 8 9 10 11 12 class Solution { public int searchInsert (int [] nums, int target) { int left=0 ,right=nums.length-1 ; while (left<=right){ int mid=left+(right-left)/2 ; if (nums[mid]==target)return mid; else if (nums[mid]<target)left=mid+1 ; else right=mid-1 ; } return left; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 class Solution { public boolean isPerfectSquare (int num) { int left=1 ,right=(num>>1 )+1 ; while (left<=right){ int mid=left+(right-left)/2 ; long sqr=(long )mid*mid; if (sqr==num)return true ; else if (sqr>num)right=mid-1 ; else left=mid+1 ; } return false ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution { public int findPeakElement (int [] nums) { int left = 0 , right = nums.length - 1 ; for (; left < right; ) { int mid = left + (right - left) / 2 ; if (nums[mid] > nums[mid + 1 ]) { right = mid; } else { left = mid + 1 ; } } return left; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public boolean searchMatrix (int [][] matrix, int target) { int m=matrix.length,n=matrix[0 ].length; int left=0 ,right=m*n-1 ; while (left<=right){ int mid=left+(right-left)/2 ; if (matrix[mid/n][mid%n]==target)return true ; if (matrix[mid/n][mid%n]<=target){ left=mid+1 ; }else { right=mid-1 ; } } return false ; } }
2.双指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public void moveZeroes (int [] nums) { int left = 0 ,right=0 ,n=nums.length; while (right<n){ if (nums[right]!=0 ){ swap(nums,left,right); left++; }right++; } } private void swap (int [] nums,int left,int right) { int temp=nums[left]; nums[left]=nums[right]; nums[right]=temp; } }
两堵墙,向里移动小的一个,有可能面积变大
如果两边相等,要不是最终答案,要不两个都不包括,不可能只包括一边
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution { public int maxArea (int [] height) { int res=0 ,left=0 ,right=height.length-1 ; while (left<right){ int minHeight = Math.min(height[left],height[right]); int width=right-left; res=Math.max(res,width*minHeight); if (height[left]<height[right])left++; else right--; }return res; } }
1 2 3 4 5 6 7 8 9 10 class Solution { public int [] twoSum(int [] nums,int target){ Map<Integer,Integer> map = new HashMap <>(); for (int i=0 ;i<nums.length;i++){ int diff = target-nums[i]; if (map.containsKey(diff))return new int []{map.get(diff),i}; map.put(nums[i],i); }return null ; } }
快慢指针
单链表数据结构 1 2 3 4 5 6 7 public class LinkList { public Object data; public LinkList next; public LinkList (Object e) { this .data=e; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class Solution { public ListNode detectCycle (ListNode head) { ListNode slow = head; ListNode fast = head; while (fast!=null &&fast.next!=null ){ fast=fast.next.next; slow=slow.next; if (fast==slow){ fast=head; while (slow!=fast){ fast=fast.next; slow=slow.next; }return slow; } }return null ; } }
1 2 3 4 5 6 7 8 9 10 11 public class Solution { public boolean hasCycle (ListNode head) { ListNode slow=head; ListNode fast=head; while (fast!=null &&fast.next!=null ){ fast=fast.next.next; slow=slow.next; if (slow==fast)return true ; }return false ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 class Solution { public void merge (int [] nums1, int m, int [] nums2, int n) { int p1 = m - 1 , p2 = n - 1 ; int tail = m + n - 1 ; int cur; while (p1 >= 0 || p2 >= 0 ) { if (p1 == -1 ) { cur = nums2[p2--]; } else if (p2 == -1 ) { cur = nums1[p1--]; } else if (nums1[p1] > nums2[p2]) { cur = nums1[p1--]; } else { cur = nums2[p2--]; } nums1[tail--] = cur; } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 class Solution { public ListNode getKthFromEnd (ListNode head, int k) { ListNode fast = head; ListNode slow = head; while (fast != null && k > 0 ) { fast = fast.next; k--; } while (fast != null ) { fast = fast.next; slow = slow.next; } return slow; } }
1 2 3 4 5 6 7 8 9 10 class Solution { public ListNode middleNode (ListNode head) { ListNode slow = head, fast = head; while (fast != null && fast.next != null ) { slow = slow.next; fast = fast.next.next; } return slow; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 import java.util.List;class Solution { public boolean isPalindrome (ListNode head) { if (head == null ) { return true ; } ListNode firstHalfEnd = endOfFirstHalf(head); ListNode secondHalfStart = reverseList(firstHalfEnd.next); ListNode p1 = head; ListNode p2 = secondHalfStart; boolean result = true ; while (result && p2 != null ) { if (p1.val != p2.val) { result = false ; } p1 = p1.next; p2 = p2.next; } firstHalfEnd.next = reverseList(secondHalfStart); return result; } private ListNode reverseList (ListNode head) { ListNode prev = null ; ListNode curr = head; while (curr != null ) { ListNode nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; } private ListNode endOfFirstHalf (ListNode head) { ListNode fast = head; ListNode slow = head; while (fast.next != null && fast.next.next != null ) { fast = fast.next.next; slow = slow.next; } return slow; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class Solution { public ListNode getIntersectionNode (ListNode headA, ListNode headB) { if (headA==null ||headB==null )return null ; ListNode you=headA,she=headB; while (you!=she){ you= you==null ? headB: you.next; she= she==null ? headA: she.next; } return you; } }
双指针two pointers 141/344/881 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 class Solution { public void reverseString (char [] s) { int left=0 ,right=s.length-1 ; char temp; while (left<right){ temp=s[left]; s[left]=s[right]; s[right]=temp; left++; right--; } } } class Solution { char temp = 0 ; public void reverseString (char [] s) { swap(s,0 ,s.length-1 ); } private void swap (char [] s,int left,int right) { while (left>right){ return ; } temp = s[left]; s[left]=s[right]; s[right]=temp; swap(s,left+1 ,right-1 ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution { public int numRescueBoats (int [] people, int limit) { int res=0 ,left=0 ,right=people.length-1 ; Arrays.sort(people); while (left<=right){ if (left==right){ res++; break ; }else if (people[left]+people[right]<=limit){ right--; left++; res++; }else { right--; res++; } } return res; } }
3.sliding window(和two sum都很重要,高频) 双指针变形,一般为同向。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 模板 def findSubArray (nums ): N = len (nums) left, right = 0 , 0 sums = 0 res = 0 while right < N: sums += nums[right] while 区间[left, right]不符合题意: sums -= nums[left] left += 1 res = max (res, right - left + 1 ) right += 1 return res
209. 长度最小的子数组 Minimum Size Subarray Sum 找连续子数组1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Solution { public int minSubArrayLen (int target, int [] nums) { int left = 0 ,N=nums.length,res=Integer.MAX_VALUE,sum=0 ; for (int i=0 ;i<N;i++){ sum += nums[i]; while (sum >= target){ res=Math.min(res,i-left+1 ); sum -= nums[left++]; } }return res==Integer.MAX_VALUE ? 0 :res; } } class Solution { public int minSubArrayLen (int target, int [] nums) { int left=0 ,right=nums.length-1 ,res=0 ; while (left<=right){ int mid=left+(right-left)/2 ; if (volidwindow(mid+1 ,nums,target)){ right=mid-1 ; res=mid+1 ; }else left=mid+1 ; }return res; } private boolean volidwindow (int size,int [] nums,int s) { int sum=0 ; for (int i=0 ;i<nums.length;i++){ sum+=nums[i]; if (i-size>=0 )sum-=nums[i-size]; if (sum>=s)return true ; }return false ; } }
340会员题目 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 class Solution { public int maxVowels (String s, int k) { char [] c=s.toCharArray(); int left=0 ,right=0 ,res=0 ,count=0 ; while (right<c.length){ if (c[right]=='a' ||c[right]=='e' ||c[right]=='i' ||c[right]=='o' ||c[right]=='u' ){ count++; } right++; if (right-left==k){ res=Math.max(res,count); if (c[left]=='a' ||c[left]=='e' ||c[left]=='i' ||c[left]=='o' ||c[left]=='u' ){ count--; } left++; } } return res; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution { public int lengthOfLongestSubstring (String s) { if (s.length()==0 )return 0 ; HashMap<Character,Integer> map = new HashMap <>(); int left=0 ,max=0 ; for (int i=0 ;i<s.length();i++){ if (map.containsKey(s.charAt(i))){ left=Math.max(left, map.get(s.charAt(i))+1 ); } map.put(s.charAt(i),i); max=Math.max(max,i-left+1 ); } return max; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution { public int longestOnes (int [] nums, int k) { int len=nums.length; int l=0 ,r=0 ,max=0 ,count0=0 ; while (r<len){ if (nums[r]==0 )count0++; r++; while (count0>k){ if (nums[l]==0 )count0--; l++; } max=Math.max(max,r-l); } return max; } }
转变一下刷题顺序,先以出新手村为目标 笔记: 一.数据结构: √1数组Array 485/283/27 √2链表Linked List 203/206 √3队列Queue 933/225(用队列实现栈)/622/641 √4栈stack 20/496/232(用栈实现队列) 单调栈模板 √5哈希表Hash table 217/389/496 √6集合set 217/705(设计) √7堆Heap 215/692 √8树&图(算法)
二.算法: √1双指针two pointers 141/344/881 √2二分查找 binary search ==704==/35/162/74 √3滑动窗口 sliding window(技巧) 209/1456 √4递归 recursion 509/206/344/687 画一画 树的先学树 5分治 divide&conquer 169/53 6回溯 backtracking 22/78/77/46(全经典) 7深度优先搜索DFS 938/78/200 8宽度优先搜索BFS 200/547/721 9并查集 union find 200/547/721 10贪心 greedy 322/1217/55 11记忆化搜索(技巧)509/322 12动态规划 dynamic programming 509/62/121/70/279/221 13拓扑排序 topologic sort 207/210 14前缀树 trie 208/720/692(数据结构)
ArrayList 动态数组:可以实现List,能增删改遍历
常用方法:get()返回第几个的值,add(),set()修改,remove()删除,size(),sort()排序
LinkedList线性链表:可以实现Queue,List;
queue常用操作:
添加到尾部:add(),offer()不报错;
peek()返回第一个,poll()返回第一个并删掉,size()长度.
1数组Array 485/283/27 ArrayList ADT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 size(); isEmpty(); contains(Object o)是否包含,不含false ; indexOf(Object o)元素下标,不存在-1 ; lastIndexOf(Object o)最大下标,不含-1 ; get(int e)获取指定下标的元素; set(int e,E element)设置指定下标的值; add(E e)队尾添加数据; add(int index,E element)指定下标添加元素,小于动态数组大小; remove(int index); remove(Object o)移除指定元素,成功返回true ,失败返回false ; clear()清除所有; sort()所有元素排序;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution { public int findMaxConsecutiveOnes (int [] nums) { int count=0 ,max=0 ; for (int i=0 ;i<nums.length;i++){ if (nums[i]==1 )count++; else if (nums[i]==0 ){ max=Math.max(max,count); count=0 ; } if (i==nums.length-1 )max=Math.max(max,count); } return max; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Solution { public int removeElement (int [] nums, int val) { int idx = 0 ; for (int x : nums) { if (x != val) nums[idx++] = x; } return idx; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { public int removeDuplicates (int [] nums) { if (nums==null ||nums.length==0 )return 0 ; int fast=1 ,slow=0 ; while (fast<nums.length){ if (nums[fast]!=nums[slow]){ nums[slow+1 ]=nums[fast]; slow++; } fast++; } return slow+1 ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public List<Integer> findDisappearedNumbers (int [] nums) { if (nums.length==0 )return null ; for (int i=0 ;i<nums.length;i++){ nums[Math.abs(nums[i])-1 ]=-Math.abs(nums[Math.abs(nums[i])-1 ]); } List<Integer> result=new ArrayList <>(); for (int i=0 ;i<nums.length;i++){ if (nums[i]>0 ) result.add(i+1 ); } return result; } }
2链表Linked List 203/206 单向链表ADT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 isEmpty(); isLast(node) node是否最后一个结点,true false ; getFirst(); setFirst(node); prepend(T obj)添加元素到链头,返回指向新节点的指针; append(T obj)添加元素到表尾,返回指向新节点指针; insert(node,T obj) node后插入新结点obj,返回新结点; remove(node); removeHead(); clear(); free(); getNthEntry(int n)返回第n个位置的元素,超出报错; length(); toArry(); findData(T obj); 迭代器?Iterator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution { public ListNode removeElements (ListNode head, int val) { ListNode dummyHead = new ListNode (0 ); dummyHead.next = head; ListNode temp = dummyHead; while (temp.next != null ) { if (temp.next.val == val) { temp.next = temp.next.next; } else { temp = temp.next; } } return dummyHead.next; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 class Solution { public ListNode reverseList (ListNode head) { ListNode prev = null ; ListNode curr = head; while (curr != null ) { ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } } class Solution { public ListNode reverseList (ListNode head) { if (head==null || head.next==null ) { return head; } ListNode cur = reverseList(head.next); head.next.next = head; head.next = null ; return cur; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public ListNode removeNthFromEnd (ListNode head, int n) { ListNode dummy = new ListNode (0 ); dummy.next=head; ListNode first = dummy, second = dummy; for (int i=0 ;i<n;i++){ first=first.next; } while (first.next!=null ){ first=first.next; second=second.next; } second.next=second.next.next; return dummy.next; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public ListNode mergeTwoLists (ListNode list1, ListNode list2) { ListNode head=new ListNode (); ListNode res=head; while (list1!=null &&list2!=null ){ if (list1.val<=list2.val){ res.next=list1; list1=list1.next; }else { res.next=list2; list2=list2.next; } res=res.next; } res.next= list1==null ?list2:list1; return head.next; } }
3队列Queue 933/225(用队列实现栈)/622/641 队列ADT: 1 2 3 4 5 6 7 8 9 10 11 12 13 add(E e)队尾加入,无可用空间报错; offer(E e)队尾加入元素,无可用返回false ; push(E e)类似与offer; remove()移除队首并返回,空报错; pop()移除队首并返回,空null ;同pull(); element()返回队首,空报错; peek()返回队首,空null ;
题目莫名其妙看不懂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class RecentCounter { Queue<Integer> q; public RecentCounter () { q = new LinkedList (); } public int ping (int t) { q.add(t); while (q.peek() < t - 3000 ) q.poll(); return q.size(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 class MyStack { Queue<Integer> queue; Queue<Integer> queue_ass; public MyStack () { queue=new LinkedList <Integer>(); queue_ass=new LinkedList <Integer>(); } public void push (int x) { queue_ass.offer(x); while (!queue.isEmpty()){ queue_ass.offer(queue.poll()); } while (!queue_ass.isEmpty()){ queue.offer(queue_ass.poll()); } } public int pop () { return queue.poll(); } public int top () { return queue.peek(); } public boolean empty () { return queue.isEmpty(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 public class MyCircularQueue { private int []arr; private int front; private int rear; private int length; public MyCircularQueue (int k) { length=k+1 ; arr=new int [length]; front=0 ; rear=0 ; } public boolean enQueue (int value) { if (isFull()){ return false ; }else { arr[rear]=value; rear=(rear+1 )%length; return true ; } } public boolean deQueue () { if (isEmpty()){ return false ; }else { front=(front+1 )%length; return true ; } } public int Front () { if (isEmpty()){ return -1 ; }else return arr[front]; } public int Rear () { if (isEmpty()){ return -1 ; }else { return arr[(rear-1 +length)%length]; } } public boolean isEmpty () { return (front==rear); } public boolean isFull () { return ((rear+1 )%length==front); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 class MyCircularDeque { private int [] arr; private int front; private int rear; private int length; public MyCircularDeque (int k) { length=k+1 ; arr=new int [length]; front=0 ; rear=0 ; } public boolean insertFront (int value) { if (isFull())return false ; else { arr[(front-1 +length)%length]=value; front=(front-1 +length)%length; return true ; } } public boolean insertLast (int value) { if (isFull())return false ; else { arr[rear]=value; rear=(rear+1 )%length; return true ; } } public boolean deleteFront () { if (isEmpty())return false ; else { front=(front+1 )%length; return true ; } } public boolean deleteLast () { if (isEmpty())return false ; else { rear=(rear-1 +length)%length; return true ; } } public int getFront () { if (isEmpty())return -1 ; else return arr[front]; } public int getRear () { if (isEmpty())return -1 ; else return arr[(rear-1 +length)%length]; } public boolean isEmpty () { if (front==rear)return true ; else return false ; } public boolean isFull () { if ((rear+1 +length)%length==front)return true ; else return false ; } }
4栈stack 20/496/232(用栈实现队列) 栈ADT: 1 2 3 4 5 6 7 8 9 10 11 stack()建立一个空栈; push(E item)栈顶插入,入栈; pop()栈顶删除返回,出栈; peek()返回栈顶元素; empty(); search(Object o)查找位置;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public boolean isValid (String s) { if (s.isEmpty())return false ; Stack<Character> stack=new Stack <Character>(); for (char c:s.toCharArray()){ if (c=='(' ) stack.push(')' ); else if (c=='[' ) stack.push(']' ); else if (c=='{' ) stack.push('}' ); else if (stack.empty()||c!=stack.pop()) return false ; } if (stack.empty()) return true ; else return false ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 vector<int > nextGreaterElement (vector<int >& nums) { vector<int > ans (nums.size() ); stack<int > s; for (int i = nums.size() - 1 ; i >= 0 ; i--) { while (!s.empty() && s.top() <= nums[i]) { s.pop(); } ans[i] = s.empty() ? -1 : s.top(); s.push(nums[i]); } return ans; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution { public int [] nextGreaterElement(int [] nums1, int [] nums2) { int [] result=new int [nums1.length]; Map<Integer,Integer>map=nextGreaterHelper(nums2); for (int i=0 ;i<nums1.length;i++){ result[i]=map.get(nums1[i]); } return result; } private Map<Integer,Integer> nextGreaterHelper (int [] nums) { Map<Integer,Integer> map=new HashMap <>(); Stack<Integer> stack=new Stack <>(); for (int i=nums.length-1 ;i>=0 ;i--){ while (!stack.empty()&& stack.peek()<=nums[i]){ stack.pop(); } map.put(nums[i],stack.isEmpty()?-1 :stack.peek()); stack.push(nums[i]); } return map; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public int [] nextGreaterElements(int [] nums) { int n=nums.length; int [] res=new int [n]; Stack<Integer> stack=new Stack <>(); for (int i=2 *n-1 ;i>=0 ;i--){ while (!stack.empty()&&stack.peek()<=nums[i%n]){ stack.pop(); } res[i%n]=stack.empty()?-1 :stack.peek(); stack.push(nums[i%n]); } return res; } }
1118.一月有多少天
5哈希表Hash table 217/389/496 1 HashSet<String> sites = new HashSet<String>();
HashSet常用 add(),contains(),remove(),size(); 1 HashMap<Integer, String> Sites = new HashMap<Integer, String>();
HashMap常用put(key,value),get(key)访问value,remove(key),size() for-each,clear(),clone(),isEmpty()通用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 class Solution { public boolean containsDuplicate (int [] nums) { Arrays.sort(nums); int n = nums.length; for (int i = 0 ; i < n - 1 ; i++) { if (nums[i] == nums[i + 1 ]) { return true ; } } return false ; } } class Solution { public boolean containsDuplicate (int [] nums) { Set<Integer> set = new HashSet <Integer>(); for (int x : nums) { if (!set.add(x)) { return true ; } } return false ; } } class Solution { public boolean containsDuplicate (int [] nums) { Set<Integer> set=new HashSet <>(); for (int x:nums)set.add(x); if (set.size()<nums.length)return true ; else return false ; } }
1 2 3 4 5 6 7 8 9 10 11 class Solution { public char findTheDifference (String s, String t) { Set<Character> set=new HashSet <>(); char [] charArr = s.concat(t).toCharArray(); for (int i=0 ;i<charArr.length;i++){ if (set.contains(charArr[i])){ set.remove(charArr[i]); }else set.add(charArr[i]); }return (char ) set.toArray()[0 ]; } }
1 2 3 4 5 6 7 8 9 10 11 12 class Solution { public int [] nextGreaterElement(int [] nums1, int [] nums2) { int [] res =new int [nums1.length]; for (int i=0 ;i<nums1.length;i++){ int j=0 ; while (j<nums2.length&&nums1[i]!=nums2[j])j++; while (j<nums2.length&&nums2[j]<=nums1[i])j++; res[i] = j<nums2.length ? nums2[j] : -1 ; }return res; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution { public int singleNumber (int [] nums) { Set<Integer>set =new HashSet <>(); for (int i:nums){ if (set.contains(i)){ set.remove(i); }else set.add(i); }return (int )set.toArray()[0 ]; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import java.util.Arrays;class Solution { public int [] intersection(int [] nums1, int [] nums2) { Set <Integer> parentSet=new HashSet <>(); Set <Integer> childSet=new HashSet <>(); for (int num:nums1){ parentSet.add(num); } for (int num:nums2){ if (parentSet.contains(num)){ childSet.add(num); } } int [] res=new int [childSet.size()]; int index=0 ; for (int value:childSet){ res[index++]=value; } return res; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Solution { public boolean isAnagram (String s, String t) { Map<Character,Integer> map=new HashMap <>(); for (char ch:s.toCharArray()){ map.put(ch,map.getOrDefault(ch,0 )+1 ); } for (char ch:t.toCharArray()){ Integer count=map.get(ch); if (count==null ){ return false ; }else if (count>1 ){ map.put(ch,count-1 ); }else { map.remove(ch); } } return map.isEmpty(); } }
HashSet.add() 不进去重复元素,会return false
而HashMap.put()会更新
1 2 3 4 5 6 7 8 class Solution { public int findRepeatNumber(int[] nums) { Set<Integer> set=new HashSet<>(); for(int num:nums){ if(!set.add(num))return num; }return -1; } }
6集合set 217/705(设计) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class MyHashSet { boolean []nodes =new boolean [10000000 ]; public MyHashSet () { } public void add (int key) { nodes[key]=true ; } public void remove (int key) { nodes[key]=false ; } public boolean contains (int key) { return nodes[key]; } }
7堆Heap 215/692
已知堆的父节点,左孩子2k+1,右孩子2k+2;
已知孩子节点k,parent (k-1)/2 int不要小数
Heapify 堆排序(大根堆、小根堆) T(N)=O(N)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 private void buildHeap (int [] A) { for (int i=A.length/2 ;i--) heapify(A,A.length,i); } static void heapify (int arr[],int n,int i) { int largest=i; int lChild=2 *i+1 ; int rChild=2 *i+2 ; if (lChild<n&&arr[lChild]>arr[largest]) largest=lChild; if (rChild<n&&arr[rChild]>arr[largest]) largest=rChild; if (largest!=i){ int temp=arr[i]; arr[i]=arr[largest]; arr[largest]=arr[i]; heapify(arr,n,largest]); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public void sort (int arr[]) { int n=arr.length; for (int i=n/2 -1 ;i>=0 ;i--) heapify(arr,n,i); for (int i=n-1 ;i>0 ;i--){ int temp=arr[0 ]; arr[0 ]=arr[i]; arr[i]=temp; heapify(arr,i,0 ); } }
PriorityQueue JAVA默认小根堆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class Solution { public int [] getLeastNumbers(int [] arr, int k) { if (k==0 ||arr.length==0 )return new int [0 ]; Queue<Integer> heap = new PriorityQueue <>((v1, v2) -> v2 - v1); for (int e:arr){ if (heap.size() < k) { heap.offer(e); } else if (e < heap.peek()) { heap.poll(); heap.offer(e); } } int [] res=new int [heap.size()]; int j=0 ; for (int e:heap){ res[j++]=e; }return res; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class KthLargest { PriorityQueue<Integer> pq; int k; public KthLargest (int k, int [] nums) { this .k = k; pq = new PriorityQueue <Integer>(); for (int x : nums) { add(x); } } public int add (int val) { pq.offer(val); if (pq.size() > k) { pq.poll(); } return pq.peek(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public int findKthLargest (int [] nums, int k) { if (nums.length<k||nums.length==0 )return -1 ; Queue<Integer> pq=new PriorityQueue <Integer>(); for (int i=0 ;i<k;i++){ pq.offer(nums[i]); } for (int i=k;i<nums.length;i++){ if (nums[i]>pq.peek()){ pq.poll(); pq.offer(nums[i]); } } return pq.peek(); } }
动态规划没看 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public int maxSubArray (int [] nums) { int result=nums[0 ]; for (int i=0 ;i<nums.length;i++){ int count=0 ,res=nums[0 ]; for (int j=i;j<nums.length;j++){ count=count+nums[j]; res=Math.max(res,count); } result=Math.max(result,res); } return result; } }
8递归 recursion 509/206/344/687 画一画 1 2 3 4 5 6 class Solution { public int fib (int n) { if (n<2 ) return n; return fib(n-1 )+fib(n-2 ); } }
9分治 divide&conquer 169/53,考的少先跳过 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution { public int majorityElement (int [] nums) { Arrays.sort(nums); return nums[(nums.length-1 )/2 ]; } }
10 扫描线 input:[[0,30],[5,10],[15,20]] outpit:false 能否同时参加
1 2 3 4 5 6 7 8 9 10 public boolean canAttendMeeting (int [][] intervals) { if (intervals.length==0 )return true ; Arrays.sor(intervals,(a,b)->a[0 ]-b[0 ]); for (int i=0 ;i<intervals.length-1 ;i++){ if (intervals[i][1 ]>intervals[i+1 ][0 ]){ return false ; } } return true ; }
input:[[0,30],[5,10],[15,20]] outpit:2 最少需要几个房间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public int minMeetingRooms (int [][] intervals) { List<int []> list = new ArrayList <>(); for (int [] interval: intervals){ list.add(new int []{interval[0 ],1 }); list.add(new int []{interval[1 ],-1 }); } Collection.sort(list,(a,b)->a[0 ]==b[0 ]?a[1 ]-b[1 ]:a[0 ]-b[0 ]); int res=0 ,count=0 ; for (int []point:list){ count +=point[1 ]; res=Math.max(res,count); } return res; }
11 树 递归法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 class Solution { public List<Integer> preorderTraversal (TreeNode root) { List<Integer> result = new ArrayList <Integer>(); preorder(root, result); return result; } public void preorder (TreeNode root, List<Integer> result) { if (root==null )return ; result.add(root.val); preorder(root.left, result); preorder(root.right, result); } } class Solution { public List<Integer> inorderTraversal (TreeNode root) { List<Integer> result = new ArrayList <Integer>(); inorder(root,result); return result; } private void inorder (TreeNode root,List result) { if (root == null )return ; inorder(root.left,result); result.add(root.val); inorder(root.right,result); } } class Solution { public List<Integer> postorderTraversal (TreeNode root) { List<Integer> result = new ArrayList <Integer>(); postorder(root, result); return result; } private void postorder (TreeNode root, List<Integer> result) { if (root == null )return ; postorder(root.left,result); postorder(root.right,result); result.add(root.val); } }
字符串中只有isEmpty()方法,其它没太大区别
迭代,好理解的思路,不同写法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 class Solution { public List<Integer> preorderTraversal (TreeNode root) { List<Integer> result = new ArrayList <Integer>(); if (root == null )return result; Stack<TreeNode> stack = new Stack <>(); stack.push(root); while (!stack.isEmpty()){ TreeNode node = stack.pop(); result.add(node.val); if (node.right!=null ){ stack.push(node.right); } if (node.left!=null ){ stack.push(node.left); } } return result; } } class Solution { public List<Integer> postorderTraversal (TreeNode root) { List<Integer> result = new ArrayList <Integer>(); if (root == null ){ return result; } Stack<TreeNode> stack = new Stack <>(); stack.push(root); while (!stack.isEmpty()){ TreeNode node = stack.pop(); result.add(node.val); if (node.left!=null ){ stack.push(node.left); } if (node.right!=null ){ stack.push(node.right); } } Collections.reverse(result); return result; } } class Solution { public List<Integer> inorderTraversal (TreeNode root) { List<Integer> result = new ArrayList <Integer>(); if (root==null ){ return result; } Stack<TreeNode> stack = new Stack <>(); TreeNode cur=root; while (cur!=null ||!stack.isEmpty()){ if (cur!=null ){ stack.push(cur); cur=cur.left; }else { cur=stack.pop(); result.add(cur.val); cur=cur.right; } } return result; } }
用标记的方法统一迭代 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 class Solution { public List<Integer> inorderTraversal (TreeNode root) { List<Integer> result=new ArrayList <Integer>(); Stack<TreeNode> stack=new Stack <>(); if (root!=null )stack.push(root); while (!stack.isEmpty()){ TreeNode node = stack.pop(); if (node!=null ){ if (node.right!=null )stack.push(node.right); stack.push(node); stack.push(null ); if (node.left!=null )stack.push(node.left); }else { node=stack.pop(); result.add(node.val); } } return result; } } class Solution { public List<Integer> preorderTraversal (TreeNode root) { List<Integer> result=new LinkedList <>(); Stack<TreeNode> stack=new Stack <>(); if (root!=null )stack.push(root); while (!stack.isEmpty()){ TreeNode node= stack.pop(); if (node!=null ){ if (node.right!=null )stack.push(node.right); if (node.left!=null )stack.push(node.left); stack.push(node); stack.push(null ); }else { node=stack.pop(); result.add(node.val); } } return result; } } class Solution { public List<Integer> postorderTraversal (TreeNode root) { List<Integer> result=new ArrayList <>(); Stack<TreeNode> stack = new Stack <>(); if (root!=null )stack.push(root); while (!stack.isEmpty()){ TreeNode node=stack.pop(); if (node!=null ){ stack.push(node); stack.push(null ); if (node.right!=null )stack.push(node.right); if (node.left!=null )stack.push(node.left); }else { node=stack.pop(); result.add(node.val); } } return result; } }
BFS 模板 1 2 3 4 5 6 7 8 9 10 11 12 13 void bfs (TreeNode root) { Queue<TreeNode> queue = new ArrayDeque <>(); queue.add(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node.left != null ) { queue.add(node.left); } if (node.right != null ) { queue.add(node.right); } } }
DFS模板 1 2 3 4 5 6 void dfs (TreeNode root) { if (root == null )return ; dfs(root.left); dfs(root.right); }
深度优先遍历递归做层次遍历 模板 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Solution { public List<List<Integer>> result=new ArrayList <List<Integer>>(); public List<List<Integer>> levelOrder (TreeNode root) { if (root==null )return result; dfs(1 , root); return result; } public void dfs (Integer deep, TreeNode root) { if (result.size()<deep){ result.add(new ArrayList <Integer>()); } result.get(deep-1 ).add(root.val); if (root.left!=null )dfs(deep+1 ,root.left); if (root.right!=null )dfs(deep+1 ,root.right); } }
广度优先遍历递归做层次遍历,队列 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Solution { public List<List<Integer>> result=new ArrayList <List<Integer>>(); public List<List<Integer>> levelOrder (TreeNode root) { if (root==null )return result; bfs(root); return result; } public void bfs (TreeNode root) { Queue<TreeNode> queue=new LinkedList <>(); queue.add(root); while (!queue.isEmpty()){ List<Integer> itemList=new ArrayList <Integer>(); int len=queue.size(); while (len>0 ){ TreeNode node=queue.poll(); itemList.add(node.val); if (node.left!=null )queue.add(node.left); if (node.right!=null )queue.add(node.right); len--; } result.add(itemList); } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 class Solution { public List<List<Integer>> result=new ArrayList <>(); public List<List<Integer>> levelOrderBottom (TreeNode root) { if (root==null )return result; dfs(1 ,root); Collections.reverse(result); return result; } private void dfs (Integer deep,TreeNode root) { if (result.size()<deep){ result.add(new ArrayList <Integer>()); } result.get(deep-1 ).add(root.val); if (root.left!=null )dfs(deep+1 ,root.left); if (root.right!=null )dfs(deep+1 ,root.right); } }
Collections.reverse()
Collections.swap()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Solution { public List<Integer> rightSideView (TreeNode root) { List<Integer> result=new ArrayList <>(); Queue<TreeNode> queue=new LinkedList <>(); if (root==null )return result; queue.add(root); while (!queue.isEmpty()){ int len=queue.size(); while (len>0 ){ TreeNode node=queue.poll(); if (node.left!=null )queue.add(node.left); if (node.right!=null )queue.add(node.right); len--; if (len==0 )result.add(node.val); } } return result; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution { public List<Double> averageOfLevels (TreeNode root) { Queue<TreeNode> queue = new LinkedList <>(); List<Double> result = new ArrayList <>(); if (root==null )return result; queue.add(root); while (!queue.isEmpty()){ int length=queue.size(); int len=length; Double sum=0.0 ; while (len>0 ){ TreeNode node=queue.poll(); if (node.left!=null )queue.add(node.left); if (node.right!=null )queue.add(node.right); sum+=node.val; len--; } result.add(sum/length); } return result; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Solution { public List<List<Integer>> levelOrder (Node root) { List<List<Integer>> list = new ArrayList <>(); Deque<Node> que = new LinkedList <>(); if (root == null ) { return list; } que.offerLast(root); while (!que.isEmpty()) { int levelSize = que.size(); List<Integer> levelList = new ArrayList <>(); for (int i = 0 ; i < levelSize; i++) { Node poll = que.pollFirst(); levelList.add(poll.val); List<Node> children = poll.children; if (children == null || children.size() == 0 ) { continue ; } for (Node child : children) { if (child != null ) { que.offerLast(child); } } } list.add(levelList); } return list; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Solution { public List<Integer> largestValues (TreeNode root) { List<Integer> result = new ArrayList <>(); if (root==null )return result; Queue<TreeNode> queue = new LinkedList <>(); queue.add(root); while (!queue.isEmpty()){ int len=queue.size(); int max=queue.peek().val; while (len>0 ){ TreeNode node = queue.poll(); if (node.left!=null )queue.add(node.left); if (node.right!=null )queue.add(node.right); max= max < node.val ? node.val : max; len--; } result.add(max); } return result; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Solution { public Node connect (Node root) { LinkedList<Node> queue = new LinkedList <>(); if (root==null )return root; queue.add(root); while (!queue.isEmpty()){ int len=queue.size(); Node node=queue.peek(); for (int i=1 ;i<len;i++){ node.next=queue.get(i); node=queue.get(i); } while (len>0 ){ node=queue.poll(); if (node.left != null ) queue.add(node.left); if (node.right != null ) queue.add(node.right); len--; } } return root; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution { public int maxDepth (TreeNode root) { Queue<TreeNode> queue= new LinkedList <>(); int deep = 0 ; if (root==null )return deep; queue.add(root); while (!queue.isEmpty()){ int len=queue.size(); while (len>0 ){ TreeNode node = queue.poll(); if (node.left!=null )queue.add(node.left); if (node.right!=null )queue.add(node.right); len--; } deep++; } return deep; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution { public int minDepth (TreeNode root) { Queue<TreeNode> queue = new LinkedList <>(); int deep=0 ; if (root==null )return deep; queue.add(root); while (!queue.isEmpty()){ int len = queue.size(); deep++; while (len>0 ){ TreeNode node = queue.poll(); if (node.left!=null )queue.add(node.left); if (node.right!=null )queue.add(node.right); if (node.left==null &&node.right==null )return deep; len--; } } return deep; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 class Solution { public TreeNode invertTree (TreeNode root) { if (root==null )return root;null 也不影响递归 swapChild(root); invertTree(root.left); invertTree(root.right); return root; } private void swapChild (TreeNode node) { TreeNode temp=node.left; node.left=node.right; node.right=temp; } }*/ class Solution { public TreeNode invertTree (TreeNode root) { Queue<TreeNode> queue=new LinkedList <>(); if (root==null )return root; queue.add(root); while (!queue.isEmpty()){ int len=queue.size(); while (len>0 ){ TreeNode node=queue.poll(); swapChild(node); if (node.left!=null )queue.add(node.left); if (node.right!=null )queue.add(node.right); len--; } } return root; } private void swapChild (TreeNode node) { TreeNode temp=node.left; node.left=node.right; node.right=temp; } }
12 10大排序算法