Array
4月3号
1. 1 Two Sum bugfree
public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(target - numbers[i])) { result[1] = i + 1; result[0] = map.get(target - numbers[i]); return result; } map.put(numbers[i], i + 1); } return result; }
2. 4 Median of Two Sorted Array 找l 和 r 找 如第k/2过返回下 如1返回小 一半递归
public double findMedianSortedArrays(int[] A, int[] B) { int m = A.length, n = B.length; int l = (m + n + 1) / 2; int r = (m + n + 2) / 2; return (getkth(A, 0, B, 0, l) + getkth(A, 0, B, 0, r)) / 2.0; } public double getkth(int[] A, int aStart, int[] B, int bStart, int k) { if (aStart > A.length - 1) return B[bStart + k - 1]; if (bStart > B.length - 1) return A[aStart + k - 1]; if (k == 1) return Math.min(A[aStart], B[bStart]); int aMid = Integer.MAX_VALUE, bMid = Integer.MAX_VALUE; if (aStart + k/2 - 1 < A.length) aMid = A[aStart + k/2 - 1]; if (bStart + k/2 - 1 < B.length) bMid = B[bStart + k/2 - 1]; if (aMid < bMid) return getkth(A, aStart + k/2, B, bStart, k - k/2);// Check: aRight + bLeft else return getkth(A, aStart, B, bStart + k/2, k - k/2);// Check: bRight + aLeft }
3, 11 Container With Most Water 左右比较找最大
public int maxArea(int[] height) { if (height == null || height.length == 0) { return 0; } int l = 0; int r = height.length - 1; int area = 0; while (l < r) { area = Math.max(area, Math.min(height[l], height[r]) * (r - l)); if (height[l] < height[r]) { l++; } else { r--; } } return area; }
4 15 3sum 转变2 sum 注意两处去重
public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> res = new LinkedList<>(); for (int i = 0; i < nums.length - 2; i++) { if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { int l = i + 1, r = nums.length - 1, sum = -nums[i]; while (l < r) { if (nums[l] + nums[r] == sum) { res.add(Arrays.asList(nums[i], nums[l], nums[r])); while (l < r && nums[l] == nums[l + 1]) l++; while (l < r && nums[r] == nums[r - 1]) r--; l++; r--; } else if (nums[l] + nums[r] > sum) { r--; } else { l++; } } } } return res; }
4 月 4号
5 16 3 Sum Closet
public int threeSumClosest(int[] nums, int target) { int res = nums[0] + nums[1] + nums[nums.length - 1]; Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i++) { int l = i + 1, r = nums.length - 1; while(l < r) { int sum = nums[l] + nums[r] + nums[i]; if (sum > target) { r--; } else { l++; } if (Math.abs(sum - target) < Math.abs(res - target)) { res = sum; } } } return res; }
6 18 4 Sum
public List<List<Integer>> fourSum(int[] nums, int target) { ArrayList<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length < 4) { return res; } Arrays.sort(nums); for (int i = 0; i < nums.length - 3; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } for (int j = i + 1; j < nums.length - 2; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } int l = j + 1, r = nums.length - 1; while (l < r) { int sum = nums[i] + nums[j] + nums[l] + nums[r]; if (sum == target) { res.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r])); while (l < r && nums[l] == nums[l + 1]) l++; while (l < r && nums[r] == nums[r - 1]) r--; l++; r--; } else if (sum > target) { r--; } else { l++; } } } } return res; }
7 26 Remove Duplicates from Sorted Array index = 1 i 和i -1 比
public int removeDuplicates(int[] nums) { int index = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] != nums[i - 1]) { nums[index++] = nums[i]; } } return index; }
8 27 Remove Element
public int removeElement(int[] nums, int val) { int index = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != val) { nums[index++] = nums[i]; } } return index; }
4 月 5号
9 31 Next Permutation 》1 交换 sec反转
public void nextPermutation(int[] nums) { if (nums == null || nums.length <= 1) { return; } int i = nums.length - 1; for (;i >= 1; i--) { if (nums[i] > nums[i - 1]) { break; } } if (i != 0) { swap(i - 1, nums); } reverse(i, nums); } public void swap(int i, int[] nums) { for (int j = nums.length - 1; i < j; j--) { if (nums[j] > nums[i]) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; break; } } } public void reverse(int index, int[] nums) { int l = index, r = nums.length - 1; while (l < r) { int temp = nums[l]; nums[l] = nums[r]; nums[r] = temp; l++; r--; } }
10. 33 Search in Rotated Array 二分 找有序 去一半 注意先比较r
public int search(int[] A, int target) { int l = 0, r = A.length - 1; while (l <= r) { int m = l + (r - l) / 2; if (A[m] == target) { return m; } if (A[m] < A[r]) { if (target > A[m] && target <= A[r]) l = m + 1; else r = m - 1; } else { if (target >= A[l] && target < A[m]) r = m - 1; else l = m + 1; } } return -1; }
11 34 Search for a range 两次二分查找 如果左 a[l] < target
public int[] searchRange(int[] nums, int target) { int[] res = {-1, -1}; if (nums == null || nums.length == 0) { return res; } int l = 0, r = nums.length - 1; while (l <= r) { int m = (r - l) / 2 + l; if (nums[m] < target) { l = m + 1; } else { r = m - 1; } } int rl = 0; r = nums.length - 1; while (rl <= r) { int m = (r - rl) / 2 + rl; if (nums[m] <= target) { rl = m + 1; } else { r = m - 1; } } if (l <= r) { res[0] = l; res[1] = r; } return res; }
12 35 Search Insert Position <= l 比目标大 r 比,比目标小
public int searchInsert(int[] nums, int target) { int l = 0, r = nums.length - 1; while (l <= r) { int m = (r - l) / 2 + l; if (nums[m] == target) { return m; } else if (nums[m] > target) { r = m - 1; } else { l = m + 1; } } return l; }
4 月 6 号
13 39 Combination Sum 递归,分三部分 可重复
public List<List<Integer>> combinationSum(int[] candidates, int target) { ArrayList<List<Integer>> res = new ArrayList<>(); Arrays.sort(candidates); if (candidates == null || candidates.length == 0) { return res; } helper(candidates, target, 0, new ArrayList<Integer>(), res); return res; } public void helper(int[] candidates, int target, int index, ArrayList<Integer> item, ArrayList<List<Integer>> res) { if (target == 0) { res.add(new ArrayList(item)); return; } else if (target < 0) { return; } else { for (int i = index; i < candidates.length; i++) { item.add(candidates[i]); helper(candidates, target - candidates[i], i, item, res); item.remove(item.size() - 1); } } }
14 40 Combination Sum II 在上面基础上去重 ,i + 1
public List<List<Integer>> combinationSum2(int[] candidates, int target) { ArrayList<List<Integer>> res = new ArrayList<>(); Arrays.sort(candidates); if (candidates == null || candidates.length == 0) { return res; } helper(candidates, target, 0, new ArrayList<Integer>(), res); return res; } public void helper(int[] candidates, int target, int index, ArrayList<Integer> item, ArrayList<List<Integer>> res) { if (target == 0) { res.add(new ArrayList(item)); return; } if (target < 0) { return; } for (int i = index; i < candidates.length; i++) { if (i > index && candidates[i] == candidates[i - 1]) continue; item.add(candidates[i]); helper(candidates, target - candidates[i], i + 1, item, res); item.remove(item.size() - 1); } }
15 216 Combination Sum III 1 到 9
public List<List<Integer>> combinationSum3(int k, int n) { ArrayList<List<Integer>> res = new ArrayList<>(); helper(n, 1, new ArrayList<Integer>(), res, k); return res; } public void helper(int target, int index, ArrayList<Integer> item, ArrayList<List<Integer>> res, int k) { if (target == 0 && item.size() == k) { res.add(new ArrayList(item)); return; } for (int i = index; i < 10; i++) { item.add(i); helper(target - i, i + 1, item, res, k); item.remove(item.size() - 1); } }
16 78 Subsets 加入 递归 删除
public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> res = new ArrayList<>(); Arrays.sort(nums); helper(nums, new ArrayList<Integer>(), res, 0); return res; } public void helper(int[] nums, ArrayList<Integer> item, List<List<Integer>> res, int start) { res.add(new ArrayList<>(item)); for (int i = start; i < nums.length; i++) { item.add(nums[i]); helper(nums, item, res, i + 1); item.remove(item.size() - 1); } }
4 月 7 号
17 90 Subsets II 删除重复
public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> res = new ArrayList<>(); Arrays.sort(nums); helper(nums, 0, new ArrayList<Integer>(), res); return res; } public void helper(int[] nums, int index, ArrayList<Integer> item, List<List<Integer>> res) { res.add(new ArrayList<>(item)); for (int i = index; i < nums.length; i++) { if (i > index && nums[i] == nums[i - 1]) continue; item.add(nums[i]); helper(nums, i + 1, item, res); item.remove(item.size() - 1); } }
18 46 Permutations 排列组合 循环
public List<List<Integer>> permute(int[] nums) { List<List<Integer>> list = new ArrayList<>(); // Arrays.sort(nums); // not necessary backtrack(list, new ArrayList<>(), nums); return list; } private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){ if(tempList.size() == nums.length){ list.add(new ArrayList<>(tempList)); } else{ for(int i = 0; i < nums.length; i++){ if(tempList.contains(nums[i])) continue; // element already exists, skip tempList.add(nums[i]); backtrack(list, tempList, nums); tempList.remove(tempList.size() - 1); } } }
19 47 Permutations II 删除重复
public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<>(); Arrays.sort(nums); helper(nums, new ArrayList<Integer>(), new boolean[nums.length], res); return res; } public void helper(int[] nums, ArrayList<Integer> item, boolean[] used, List<List<Integer>> res) { if (item.size() == nums.length) { res.add(new ArrayList<Integer>(item)); return; } for (int i = 0; i < nums.length; i++) { if (used[i] || i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; item.add(nums[i]); used[i] = true; helper(nums, item, used, res); used[i] = false; item.remove(item.size() - 1); } }
20 131 Palindrome Partitioning 检测 递归 重复
public List<List<String>> partition(String s) { List<List<String>> res = new ArrayList<>(); helper(s, 0, new ArrayList<String>(), res); return res; } public void helper(String s, int start, ArrayList<String> item, List<List<String>> res) { if (start == s.length()) { res.add(new ArrayList<String>(item)); return; } for (int i = start; i < s.length(); i++) { if (isPalin(s, start, i)) { item.add(s.substring(start, i + 1)); helper(s, i + 1, item, res); item.remove(item.size() - 1); } } } public boolean isPalin(String s, int l, int r) { while (l < r) { if (s.charAt(l) != s.charAt(r)) { return false; } l++; r--; } return true; }
4 月 9 号
21 41 First Missing Positive 找到数字的正确位置 a[i] - 1 = i 一定先存储a[a[i] - 1] 比如num == 5 ,把他放到num[4]位置上
public int firstMissingPositive(int[] nums) { for (int i = 0; i < nums.length; i++) { while (nums[i] > 0 && nums[i] <= nums.length && nums[nums[i] - 1] != nums[i]) { int temp = nums[nums[i] - 1]; nums[nums[i] - 1] = nums[i]; nums[i] = temp; } } for (int i = 0; i < nums.length; i++) { if (nums[i] != i + 1) { return i + 1; } } return nums.length + 1; }
22 42 Trapping Rain Water 找两边最大值的最小,减去那边的值 找出每个的左右边界
public int trap(int[] height) { int l = 0, r = height.length - 1, count = 0; int maxL = 0, maxR = 0; while (l <= r) { maxL = maxL > height[l] ? maxL : height[l]; maxR = maxR > height[r] ? maxR : height[r]; if (maxL < maxR) { count += maxL - height[l]; l++; } else { count += maxR - height[r]; r--; } } return count; }
23 55 Jump Game 维护到第i步走到的最大距离
public boolean canJump(int[] nums) { int reach = 0; for (int i = 0; i < nums.length && i <= reach; i++) { reach = Math.max(reach, nums[i] + i); } if (reach < nums.length - 1) { return false; } return true; }
24 45 Jump Game II BFS 动态规划
public int jump(int[] nums) { if (n < 2) return 0; int curMax = 0, nextMax = 0, leve = 0, i = 0; while (curMax - i + 1 > 0) { leve++; for (; i <= curMax; i++) { nextMax = Math.max(nextMax, i + nums[i]); if (naxtMax >= nums.length - 1) return true; } curMax = nextMax; } return 0; }
public int jump(int[] nums) { if (nums == null || nums.length ==0) return 0; int curMax = 0, nextMax = 0, leve = 0; for (int i = 0; i <= nextMax && i < nums.length; i++) { if (i > curMax) { leve ++; curMax = nextMax; } nextMax = Math.max(nextMax, i + nums[i]); } if (nextMax < nums.length - 1) { return 0; } return leve; }
4 月 10 号
25 48 Rotate Image 上下交换 \ 角线交换
public void rotate(int[][] matrix) { int n = matrix.length; for (int i = 0; i < n / 2; i++) { for (int j = 0; j < n; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[n - 1 - i][j]; matrix[n - 1 - i][j] = temp; } } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } }
26 53 Maximum Subarray 动态规划
public int maxSubArray(int[] nums) { int n = nums.length; int[] dp = new int[n]; dp[0] = nums[0]; int max = dp[0]; for (int i = 1; i < n; i++) { dp[i] = dp[i - 1] > 0 ? dp[i - 1] + nums[i] : nums[i]; max = Math.max(max, dp[i]); } return max; }
27 54 Spiral Matrix 四个变量 行列开尾
public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<Integer>(); if (matrix == null || matrix.length == 0) { return res; } int rowB = 0, rowE = matrix.length - 1; int colB = 0, colE = matrix[0].length - 1; while (rowB <= rowE && colB <= colE) { for (int j = colB; j <= colE; j++) { res.add(matrix[rowB][j]); } rowB++; for (int j = rowB; j <= rowE; j++) { res.add(matrix[j][colE]); } colE--; if (rowB <= rowE) { for (int j = colE; j >= colB; j--) { res.add(matrix[rowE][j]); } } rowE--; if (colB <= colE) { for (int j = rowE; j >= rowB; j--) { res.add(matrix[j][colB]); } } colB++; } return res; }
28 59 Spiral Matrix II
public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int rowB = 0, rowE = n - 1; int colB = 0, colE = n - 1, num = 1; while (rowB <= rowE && colB <= colE) { for (int i = colB; i <= colE; i++) { res[rowB][i] = num++; } rowB++; for (int i = rowB; i <= rowE; i++) { res[i][colE] = num++; } colE--; for (int i = colE; i >= colB; i--) { if (rowB <= rowE) { res[rowE][i] = num++; } } rowE--; for (int i = rowE; i >= rowB; i--) { if (colB <= colE) { res[i][colB] = num++; } } colB++; } return res; }
4 月 11 号
29 56 Merge Intervals 排序开始 头尾 遍历
public List<Interval> merge(List<Interval> intervals) { if (intervals.size() <= 1) { return intervals; } intervals.sort((i1,i2) -> Integer.compare(i1.start,i2.start)); List<Interval> list = new ArrayList<Interval>(); int start = intervals.get(0).start; int end = intervals.get(0).end; for (Interval interval : intervals) { if (interval.start <= end) { end = Math.max(end, interval.end); } else { list.add(new Interval(start, end)); start = interval.start; end = interval.end; } } list.add(new Interval(start, end)); return list; }
30 57 Insert Interval 找到插入位置 遍历 改变插入
public List<Interval> insert(List<Interval> intervals, Interval in) { List<Interval> list = new ArrayList<>(); for (Interval i : intervals) { if (in == null || i.end < in.start) { list.add(i); } else if (i.start > in.end) { list.add(in); list.add(i); in = null; }else { in.start = Math.min(i.start, in.start); in.end = Math.max(i.end, in.end); } } if (in != null) { list.add(in); } return list; }
31 62 Unique Paths 动态规划res[j] +=res[j-1]
public int uniquePaths(int m, int n) { if (m <= 0 || n <= 0) { return 0; } int[] res = new int[n]; res[0] = 1; for (int i = 0; i < m; i++) { for (int j = 1; j < n; j++) { res[j] += res[j - 1]; } } return res[n - 1]; }
32 Unique Paths II
public int uniquePathsWithObstacles(int[][] obstacleGrid) { int[] res = new int[obstacleGrid[0].length]; res[0] = 1; for (int i = 0; i < obstacleGrid.length; i++) { for (int j = 0; j < obstacleGrid[0].length; j++) { if (obstacleGrid[i][j] == 1) { res[j] = 0; } else { if (j > 0) { res[j] += res[j - 1]; } } } } return res[obstacleGrid[0].length - 1]; }
4 月 12号
33 64 Minmum Path Sum 动态规划 ,比较左上 取小
public int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; int[] res = new int[n]; res[0] = grid[0][0]; for (int i = 1; i < n; i++) { res[i] = res[i - 1] + grid[0][i]; } for (int i = 1; i < m; i++) { for (int j = 0; j < n; j++) { if (j == 0) { res[j] = res[j] + grid[i][j]; }else { res[j] = Math.min(res[j - 1], res[j]) + grid[i][j]; } } } return res[n - 1]; }
34 66 Plus One 从后往前遍历 比较9
for (int i = digits.length - 1; i >= 0; i--) { if (digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] res = new int[digits.length + 1]; res[0] = 1; return res; }
35 73 Set Matrix Zeroes 第一行第一列标记 从后向前 col0
public void setZeroes(int[][] matrix) { int col0 = 1, rows = matrix.length, cols = matrix[0].length; for (int i = 0; i < rows; i++) { if (matrix[i][0] == 0) col0 = 0; for (int j = 1; j < cols; j++) if (matrix[i][j] == 0) matrix[i][0] = matrix[0][j] = 0; } for (int i = rows - 1; i >= 0; i--) { for (int j = cols - 1; j >= 1; j--) if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0; if (col0 == 0) matrix[i][0] = 0; } }
36 74 Search a 2D Matrix 二分查找 ,找对行和列
public boolean searchMatrix(int[][] matrix, int target) { int row_num = matrix.length; int col_num = matrix[0].length; int begin = 0, end = row_num * col_num - 1; while(begin <= end){ int mid = (begin + end) / 2; int mid_value = matrix[mid/col_num][mid%col_num]; if( mid_value == target){ return true; }else if(mid_value < target){ //Should move a bit further, otherwise dead loop. begin = mid+1; }else{ end = mid-1; } } return false; }
4 月 13 号
37 75 Sort Colors i3, i2, i1 先检测0
public void sortColors(int[] nums) { int i0 = 0, i1 = 0, i2 = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) { nums[i2++] = 2; nums[i1++] = 1; nums[i0++] = 0; } else if (nums[i] == 1) { nums[i2++] = 2; nums[i1++] = 1; }else { i2++; } } }
38 79 Word Search 深度优先搜索
public boolean exist(char[][] board, String word) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (help(board, i, j, word, 0)) { return true; } } } return false; } public boolean help(char[][] board, int i, int j, String word, int start) { if (start >= word.length()) return true; if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false; if (board[i][j] == word.charAt(start++)) { char c = board[i][j]; board[i][j] = '#'; boolean res = help(board, i - 1, j, word, start) || help(board, i + 1, j, word, start) || help(board, i, j - 1, word, start) || help(board, i, j + 1, word, start); board[i][j] = c; return res; } return false; }
39 80 Remvove Duplicates from Sorted Array II 遍历, 比较i个和i-2个
public int removeDuplicates(int[] nums) { int i = 0; for (int n : nums) { if (i < 2 || n > nums[i - 2]) { nums[i++] = n; } } return i; }
40 81 Search in Rotated Array 二分 比较左边
public boolean search(int[] nums, int target) { int l = 0, r = nums.length - 1; while (l <= r) { int m = (r - l) / 2 + l; if (nums[m] == target) return true; if (nums[m] > nums[l]) { if (nums[l] <= target && target < nums[m]) { r = m - 1; }else { l = m + 1; } }else if (nums[m] < nums[l]) { if (nums[m] < target && target <= nums[r]) { l = m + 1; }else { r = m - 1; } }else { l++; } } return false; }
4 月 14 号
41 84 Largest Rectangle in Histogram 维护栈 最后加0
public int largestRectangleArea(int[] heights) { int len = heights.length; int max = 0; Stack<Integer> stack = new Stack<>(); for (int i = 0; i <= len; i++) { int h = i == len ? 0: heights[i]; if (stack.isEmpty() || h >= heights[stack.peek()]) { stack.push(i); } else { int tp = stack.pop(); max = Math.max(max, heights[tp] * (stack.isEmpty() ? i : i - 1 - stack.peek())); i--; } } return max; }
42 85 Maximal Rectangle 用上一个题的答案
public int maximalRectangle(char[][] matrix) { if(matrix==null || matrix.length==0 || matrix[0].length==0) { return 0; } int maxArea = 0; int[] height = new int[matrix[0].length]; for(int i=0;i<matrix.length;i++) { for(int j=0;j<matrix[0].length;j++) { height[j] = matrix[i][j]=='0'?0:height[j]+1; } maxArea = Math.max(large(height),maxArea); } return maxArea; } public int large(int[] heights) { int len = heights.length; int max = 0; Stack<Integer> stack = new Stack<>(); for (int i = 0; i <= len; i++) { int h = i == len ? 0: heights[i]; if (stack.isEmpty() || h >= heights[stack.peek()]) { stack.push(i); } else { int tp = stack.pop(); max = Math.max(max, heights[tp] * (stack.isEmpty() ? i : i - 1 - stack.peek())); i--; } } return max; }
43 88 Merge Sorted Array 三个标志 》0
public void merge(int[] nums1, int m, int[] nums2, int n) { int i = m - 1, j = n - 1, k = m + n - 1; while (i >= 0 && j >= 0) nums1[k--] = (nums1[i] > nums2[j]) ? nums1[i--] : nums2[j--]; while (j >= 0) nums1[k--] = nums2[j--]; }
44 105 Construct Binary Tree from Preorder Inorder Traverals
public TreeNode buildTree(int[] preorder, int[] inorder) { return helper(0, 0, inorder.length - 1, preorder, inorder); } public TreeNode helper(int pres, int ins, int ine, int[] pre, int[] in) { if (pres > pre.length - 1 || ins > ine) return null; TreeNode root = new TreeNode(pre[pres]); int index = ins; for (int i = ins; i <= ine; i++) { if (in[i] == root.val) { index = i; } } root.left = helper(pres + 1, ins, index - 1, pre, in); root.right = helper(pres + index - ins + 1, index + 1, ine, pre, in); return root; }
4 月 15 日
45 106 Construct Binary Tree from Inorder Postorder Traverals\
public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder==null || postorder==null || inorder.length==0 || postorder.length==0) { return null; } HashMap<Integer,Integer> map = new HashMap<>(); for (int i = 0; i < inorder.length; i++) { map.put(inorder[i],i); } return help(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, map); } public TreeNode help(int[] in, int ins, int ine, int[] po, int ps, int pe, HashMap<Integer,Integer> map) { if (ins > ine || ps > pe) { return null; } TreeNode root = new TreeNode(po[pe]); int index = map.get(root.val); root.left = help(in, ins, index - 1, po, ps, pe - (ine - index) - 1, map); root.right = help(in, index + 1, ine, po, pe - (ine - index), pe - 1, map); return root; }
46 118 pascal's Triangle j = 1; j = j+1
public List<List<Integer>> generate(int numRows) { List<List<Integer>> list = new ArrayList<>(); List<Integer> row = new ArrayList<>(); for (int i = 0; i < numRows; i++) { row.add(0, 1); for (int j = 1; j < row.size() - 1; j++) { row.set(j, row.get(j) + row.get(j + 1)); } list.add(new ArrayList<Integer>(row)); } return list; }
47 119 Pascal's Triangle II
public List<Integer> getRow(int n) { if (n < 0) return null; List<Integer> list = new ArrayList<>(); for (int i = 0; i < n+1; i++) { list.add(0,1); for (int j = 1; j < list.size() - 1; j++) { list.set(j, list.get(j) + list.get(j + 1)); } } return list; }
48 120 Triangle 找小从下往上加
public int minimumTotal(List<List<Integer>> triangle) { for (int i = triangle.size() - 2; i >= 0; i--) for (int j = 0; j <= i; j++) triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1))); return triangle.get(0).get(0); }
4 月 16 号
49 121 BestTime to Buy and Sell Stock 如果正就加
public int maxProfit(int[] prices) { int maxc = 0, maxso = 0; for (int i = 1; i < prices.length; i++) { maxc = Math.max(0, maxc+=prices[i] - prices[i-1]); maxso = Math.max(maxso, maxc); } return maxso; }
50 122 Best Time to Buy and Sell Stock II
public int maxProfit(int[] prices) { int total = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) { total += prices[i] - prices[i - 1]; } } return total; }
51 123 Best time to buy and sell stock III 4个变量 两买 两买 最大
public int maxProfit(int[] prices) { int sell1 = 0, sell2 = 0, buy1 = Integer.MIN_VALUE, buy2 = Integer.MIN_VALUE; for (int i = 0; i < prices.length; i++) { buy1 = Math.max(buy1, -prices[i]); sell1 = Math.max(sell1, buy1 + prices[i]); buy2 = Math.max(buy2, sell1-prices[i]); sell2 = Math.max(sell2, buy2 + prices[i]); } return sell2; }
public int maxProfit(int[] prices) { if(prices==null || prices.length==0) return 0; int[] local = new int[3]; int[] global = new int[3]; for(int i=0;i<prices.length-1;i++) { int diff = prices[i+1]-prices[i]; for(int j=2;j>=1;j--) { local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff); global[j] = Math.max(local[j],global[j]); } } return global[2]; }
52 128 Longest Consecutive Sequence 维护最大序列长度
public int longestConsecutive(int[] nums) { HashMap<Integer, Integer> map = new HashMap<>(); int res = 0; for (int n : nums) { if (!map.containsKey(n)) { int left = map.containsKey(n - 1) ? map.get(n - 1):0; int right = map.containsKey(n + 1) ? map.get(n + 1):0; int sum = right + left + 1; res = res > sum ? res:sum; map.put(n, sum); map.put(n - left, sum); map.put(n + right, sum); } } return res; }
4 月 17 号
53 152 Maximum Product Subarray 保存到现在最大,最小 ,全局最大 动态规划
public int maxProduct(int[] nums) { if (nums == null || nums.length == 0) return 0; if (nums.length < 2) return nums[0]; int max = nums[0], min = nums[0], global = nums[0]; for (int i = 1; i < nums.length; i++) { int a = max * nums[i]; int b = min * nums[i]; max = Math.max(nums[i], Math.max(a,b)); min = Math.min(nums[i], Math.min(a, b)); global = Math.max(max, global); } return global; }
54 153 Find Minimum in Rotated Array 二分查找 如果左边小,就是左边
public int findMin(int[] nums) { int l = 0, r = nums.length - 1; while (l < r) { if (nums[l] < nums[r]) return nums[l]; int m = l + (r - l) / 2; if (nums[m] >= nums[l]) l = m + 1; else r = m; } return nums[l]; }
55 154 Find Minmum in Rotated Sorted Array II
public int findMin(int[] nums) { int l = 0, r = nums.length - 1; while (l < r) { if (nums[l] < nums[r]) return nums[l]; int m = l + (r - l) / 2; if (nums[m] > nums[l]) l = m + 1; else if (nums[m] < nums[l]) r = m; else l++; } return nums[l]; }
56 162 Find peak Element 根据条件二分查找
public int findPeakElement(int[] num) { if (num.length <= 1) return 0; int mid = 0, l = 0, h = num.length - 1; while (l < h) { mid = (l + h) / 2; if (num[mid] > num[mid + 1]) h = mid; else if (num[mid] < num[mid + 1]) l = mid + 1; } return l; }
4 月 18 号
57 163 Missing Range l r 找范围
public List<String> findMissingRanges(int[] nums, int lower, int upper) { List<String> res = new ArrayList<>(); int l = lower; for (int i = 0; i <= nums.length; i++) { int r = (i < nums.length && nums[i] <= upper) ? nums[i]:upper + 1; if (l == r) l = r + 1; else if (r > l) { res.add(r - l == 1 ? String.valueOf(l):from + "->" + (to - 1); l = r + 1; } } return res; }
58 167 Two sum ii 已排序 首位指针 加逼
public int[] twoSum(int[] numbers, int target) { int[] res = new int[2]; if (numbers == null || numbers.length < 2) return res; int l = 0, r = numbers.length - 1; while (l < r) { int v = numbers[l] + numbers[r]; if (v == target) { res[0] = l + 1; res[1] = r + 1; break; } else if (v > target) r--; else l++; } return res; }
59 169 Majority Element 两个变量 ,值和数 从第一个开始
public int majorityElement(int[] nums) { int major = nums[0], count = 1; for (int i = 1; i < nums.length; i++) { if (count == 0) { major = nums[i]; count++; } else if (major == nums[i]) { count ++; }else { count --; } } return major; }
60 189 Rotate Array 三部移动
public void rotate(int[] nums, int k) { k %= nums.length; reverse(nums, 0, nums.length - 1); reverse(nums, 0, k - 1); reverse(nums, k, nums.length - 1); } public void reverse(int[] nums, int l, int r) { while (l < r) { int temp = nums[l]; nums[l] = nums[r]; nums[r] = temp; l++;r--; } }
4月19 号
61 209 Minimum Size Subarry Sum 维护四个变量左右边界,总 小
public int minSubArrayLen(int s, int[] nums) { if (nums == null || nums.length == 0) return 0; int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE; while (j < nums.length) { sum += nums[j++]; while (sum >= s) { min = Math.min(min, j - i); sum -= nums[i++]; } } return min == Integer.MAX_VALUE? 0 : min; }
62 217 Contains Duplicate hashMap 遍历
public boolean containsDuplicate(int[] nums) { HashSet<Integer> res = new HashSet<Integer>(); for (int n: nums) { if (res.contains(n)) return true; res.add(n); } return false; }
63 219 Contains Duplicate II hashset i >k 删i-k-1 插入 检测
public boolean containsNearbyDuplicate(int[] nums, int k) { HashSet<Integer> set = new HashSet<Integer>(); for (int i = 0; i < nums.length; i++) { if (i > k) set.remove(nums[i - k - 1]); if (!set.add(nums[i])) return true; } return false; }
64 228 Summary Ranges 检测左右边界
public List<String> summaryRanges(int[] nums) { int len = nums.length; List<String> res = new ArrayList<>(len); for (int i = 0; i < len; i++) { int num = nums[i]; while (i < len - 1 && nums[i] + 1 == nums[i + 1]) i++; if (num == nums[i]) res.add(num+""); else res.add(num + "->" + nums[i]); } return res; }
4 月 20 号
65 229 Majority Element II 把检测是否相同放前面
public List<Integer> majorityElement(int[] nums) { List<Integer> res = new ArrayList<Integer>(); if (nums == null || nums.length == 0) return res; int num1 = 0, num2 = 0, c1 = 0, c2 = 0; for (int i = 0; i < nums.length; i++) { if (num2 == nums[i]) { c2++; } else if(num1 == nums[i]) { c1++; } else if (c1 == 0) { num1 = nums[i]; c1 = 1; } else if(c2 == 0) { num2 = nums[i]; c2 = 1; } else { c1--; c2--; } } c1 = 0; c2 = 0; for (int i = 0; i < nums.length; i++) { if (num1 == nums[i]) c1++; else if (num2 == nums[i]) c2++; } if (c1 > nums.length / 3) res.add(num1); if (c2 > nums.length / 3) res.add(num2); return res; }
66 238 Product of Array Except Self 先从左扫描,在从右扫描
public int[] productExceptSelf(int[] nums) { int len = nums.length; int[] res = new int[len]; res[0] = 1; for (int i = 1; i < len; i++) { res[i] = res[i -1] * nums[i - 1]; } int right = 1; for (int i = len - 1; i >= 0; i--) { res[i] *= right; right *= nums[i]; } return res; }
67 243 Short Words Distance 遍历数组,当遍历到单词时记录位置
public int shortestDistance(String[] words, String word1, String word2) { if (words == null) return -1; int idx1 = -1, idx2 = -1; int diff = words.length; for (int i = 0; i < words.length; i++) { if (words[i].equals(word1)) { idx1 = i; } else if (words[i].equals(word2)) { idx2 = i; } if(idx1!=-1&&idx2!=-1){ diff = Math.min(diff,Math.abs(idx1-idx2)); } } return diff; }
68 Short Words Distance II hashmap 表,先找到单词下标表 在找两个小的比较,每次跳过较小的
public class WordDistance { HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>(); public WordDistance(String[] words) { // 统计每个单词出现的下标存入哈希表中 for(int i = 0; i < words.length; i++){ List<Integer> cnt = map.get(words[i]); if(cnt == null){ cnt = new ArrayList<Integer>(); } cnt.add(i); map.put(words[i], cnt); } } public int shortest(String word1, String word2) { List<Integer> idx1 = map.get(word1); List<Integer> idx2 = map.get(word2); int distance = Integer.MAX_VALUE; int i = 0, j = 0; // 每次比较两个下标列表最小的下标,然后把跳过较小的那个 while(i < idx1.size() && j < idx2.size()){ distance = Math.min(Math.abs(idx1.get(i) - idx2.get(j)), distance); if(idx1.get(i) < idx2.get(j)){ i++; } else { j++; } } return distance; }
69 245 Short words Distance II 用一个标志是否是一样的
public int shortestWordDistance(String[] words, String word1, String word2) { int idx1 = -1, idx2 = -1, distance = Integer.MAX_VALUE, turn = 0, inc = (word1.equals(word2) ? 1 : 0); for(int i = 0; i < words.length; i++){ if(words[i].equals(word1) && turn % 2 == 0){ idx1 = i; if(idx2 != -1) distance = Math.min(distance, idx1 - idx2); turn += inc; } else if(words[i].equals(word2)){ idx2 = i; if(idx1 != -1) distance = Math.min(distance, idx2 - idx1); turn += inc; } } return distance; }