[关闭]
@Yano 2015-12-30T03:20:27.000000Z 字数 39021 阅读 33155

LeetCode之Array题目汇总

LeetCode

我的博客:http://blog.csdn.net/yano_nankai
LeetCode题解:https://github.com/LjyYano/LeetCode


LeetCode 题目汇总

LeetCode之Array题目汇总
LeetCode之Hash Table题目汇总
LeetCode之Linked List题目汇总
LeetCode之Math题目汇总
LeetCode之String题目汇总
LeetCode之Binary Search题目汇总
LeetCode之Divide and Conquer题目汇总
LeetCode之Dynamic Programming题目汇总
LeetCode之Backtracing题目汇总
LeetCode之Stack题目汇总
LeetCode之Sort题目汇总
LeetCode之Bit Manipulation题目汇总
LeetCode之Tree题目汇总
LeetCode之Depth-first Search题目汇总
LeetCode之Breadth-first Search题目汇总
LeetCode之Graph题目汇总
LeetCode之Trie题目汇总
LeetCode之Design题目汇总


文章目录:


Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


参考:LeetCode 001 Two Sum

  1. public int[] twoSum(int[] nums, int target) {
  2. if (nums == null || nums.length <= 1) {
  3. return new int[2];
  4. }
  5. Map<Integer, Integer> map = new HashMap<Integer, Integer>();
  6. // key = target - nums[i], just one solution
  7. for (int i = 0; i < nums.length; i++) {
  8. map.put(target - nums[i], i);
  9. }
  10. for (int i = 0; i < nums.length; i++) {
  11. Integer v = map.get(nums[i]);
  12. // can't use itself
  13. if (v != null && v != i) {
  14. return new int[] { i + 1, v + 1 };
  15. }
  16. }
  17. return null;
  18. }

3Sum

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:


参考:LeetCode 015 3Sum

分析:

  1. 对数组进行排序;
  2. start从0到n-1,对num[start]求另外两个数,这里用mid和end;
  3. mid指向start+1,q指向结尾。sum = num[start] + num[mid]+ num[end];
  4. 利用加逼定理求解,终止条件是mid == end;
  5. 顺带去重

去重:

  1. 如果start到了start+1,num[start] == num[start - 1],则求出的解肯定重复了;
  2. 如果mid++,num[mid] = num[mid - 1],则求出的解肯定重复了。
  1. public List<List<Integer>> threeSum(int[] nums) {
  2. if (nums == null || nums.length < 3) {
  3. return new ArrayList<List<Integer>>();
  4. }
  5. Set<List<Integer>> set = new HashSet<List<Integer>>();
  6. Arrays.sort(nums);
  7. for (int start = 0; start < nums.length; start++) {
  8. if (start != 0 && nums[start - 1] == nums[start]) {
  9. continue;
  10. }
  11. int mid = start + 1, end = nums.length - 1;
  12. while (mid < end) {
  13. int sum = nums[start] + nums[mid] + nums[end];
  14. if (sum == 0) {
  15. List<Integer> tmp = new ArrayList<Integer>();
  16. tmp.add(nums[start]);
  17. tmp.add(nums[mid]);
  18. tmp.add(nums[end]);
  19. set.add(tmp);
  20. while (++mid < end && nums[mid - 1] == nums[mid])
  21. ;
  22. while (--end > mid && nums[end + 1] == nums[end])
  23. ;
  24. }
  25. else if (sum < 0) {
  26. mid++;
  27. }
  28. else {
  29. end--;
  30. }
  31. }
  32. }
  33. return new ArrayList<List<Integer>>(set);
  34. }

3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

参考:LeetCode 016 3Sum Closest

  1. public int threeSumClosest(int[] nums, int target) {
  2. if (nums == null || nums.length < 3) {
  3. return Integer.MIN_VALUE;
  4. }
  5. Arrays.sort(nums);
  6. int minGap = Integer.MAX_VALUE;
  7. int result = 0;
  8. for (int start = 0; start < nums.length; start++) {
  9. int mid = start + 1, end = nums.length - 1;
  10. while (mid < end) {
  11. int sum = nums[start] + nums[mid] + nums[end];
  12. int gap = Math.abs(sum - target);
  13. if (gap < minGap) {
  14. minGap = gap;
  15. result = sum;
  16. }
  17. if (sum < target) {
  18. mid++;
  19. } else {
  20. end--;
  21. }
  22. }
  23. }
  24. return result;
  25. }

4Sum

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

A solution set is:
(-1,  0, 0, 1)
(-2, -1, 1, 2)
(-2,  0, 0, 2)

参考:LeetCode 018 4Sum

  1. public List<List<Integer>> fourSum(int[] nums, int target) {
  2. if (nums == null || nums.length < 4) {
  3. return new ArrayList<List<Integer>>();
  4. }
  5. Arrays.sort(nums);
  6. Set<List<Integer>> set = new HashSet<List<Integer>>();
  7. // 和3Sum一样,只是多了一个循环
  8. for (int a = 0; a < nums.length - 3; a++) {
  9. int target_3Sum = target - nums[a];
  10. for (int b = a + 1; b < nums.length - 2; b++) {
  11. int c = b + 1, d = nums.length - 1;
  12. while (c < d) {
  13. int sum = nums[b] + nums[c] + nums[d];
  14. if (sum == target_3Sum) {
  15. // 将结果加入集合
  16. List<Integer> tmp = new ArrayList<Integer>();
  17. tmp.add(nums[a]);
  18. tmp.add(nums[b]);
  19. tmp.add(nums[c]);
  20. tmp.add(nums[d]);
  21. set.add(tmp);
  22. // 去重
  23. while (++c < d && nums[c - 1] == nums[c])
  24. ;
  25. while (--d > c && nums[d + 1] == nums[d])
  26. ;
  27. }
  28. else if (sum < target_3Sum) {
  29. c++;
  30. } else {
  31. d--;
  32. }
  33. }
  34. }
  35. }
  36. return new ArrayList<List<Integer>>(set);
  37. }

Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.


参考:LeetCode 121 Best Time to Buy and Sell Stock

prices 7 2 3 6 1 9
lowest 7 2 2 2 1 1
maxProfit 0 0 1 4 4 8
  1. public int maxProfit(int[] prices) {
  2. if (prices.length <= 1) {
  3. return 0;
  4. }
  5. int maxProfit = 0;
  6. int lowest = Integer.MAX_VALUE;
  7. for (int v : prices) {
  8. lowest = Math.min(v, lowest);
  9. maxProfit = Math.max(maxProfit, v - lowest);
  10. }
  11. return maxProfit;
  12. }

Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


参考:LeetCode 122 Best Time to Buy and Sell Stock II

只要有利润就卖,就是最优解。

prices 7 2 3 6 1 9
profit 0 0 1 4 4 12
  1. public int maxProfit(int[] prices) {
  2. int profit = 0;
  3. for (int i = 1; i < prices.length; i++) {
  4. if (prices[i - 1] < prices[i]) {
  5. profit += prices[i] - prices[i - 1];
  6. }
  7. }
  8. return profit;
  9. }

Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]


参考:LeetCode 039 Combination Sum

使用递归,注意保存结果时,应该新建一个ArrayList:result.add(new ArrayList< Integer>(cur))。否则result会指向一直变化的cur。

  1. public List<List<Integer>> combinationSum(int[] candidates, int target) {
  2. if (candidates == null || candidates.length == 0) {
  3. return new ArrayList<List<Integer>>();
  4. }
  5. List<List<Integer>> result = new ArrayList<List<Integer>>();
  6. ArrayList<Integer> cur = new ArrayList<Integer>();
  7. Arrays.sort(candidates);
  8. dfs(0, target, result, cur, candidates);
  9. return result;
  10. }
  11. private void dfs(int start, int target, List<List<Integer>> result,
  12. ArrayList<Integer> cur, int[] candidates) {
  13. if (target == 0) {
  14. result.add(new ArrayList<Integer>(cur));
  15. return;
  16. }
  17. for (int i = start; i < candidates.length; i++) {
  18. // candidates[i] > target,则递归结束,后面不可能是解
  19. if (candidates[i] > target) {
  20. return;
  21. }
  22. cur.add(candidates[i]);
  23. dfs(i, target - candidates[i], result, cur, candidates);
  24. cur.remove(cur.size() - 1);
  25. }
  26. }

Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]


参考:LeetCode 040 Combination Sum II

  1. Combination Sum每个元素可以使用多次,所以递归是dfs(i, target - candidates[i], result, cur, candidates);
  2. Combination Sum II每个元素只能使用一次,所以递归是dfs(i + 1, target - candidates[i], rt, cur, candidates);因为解可能重复,所以使用set,最后转成list。
  1. public List<List<Integer>> combinationSum2(int[] candidates, int target) {
  2. if (candidates == null || candidates.length == 0) {
  3. return new ArrayList<List<Integer>>();
  4. }
  5. Set<List<Integer>> rt = new HashSet<List<Integer>>();
  6. ArrayList<Integer> cur = new ArrayList<Integer>();
  7. Arrays.sort(candidates);
  8. dfs(0, target, rt, cur, candidates);
  9. return new ArrayList<List<Integer>>(rt);
  10. }
  11. private void dfs(int start, int target, Set<List<Integer>> rt,
  12. ArrayList<Integer> cur, int[] candidates) {
  13. if (target == 0) {
  14. rt.add(new ArrayList<Integer>(cur));
  15. return;
  16. }
  17. for (int i = start; i < candidates.length; i++) {
  18. // candidates[i] > target,则递归结束,后面不可能是解
  19. if (candidates[i] > target) {
  20. return;
  21. }
  22. cur.add(candidates[i]);
  23. dfs(i + 1, target - candidates[i], rt, cur, candidates);
  24. cur.remove(cur.size() - 1);
  25. }
  26. }

Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.

Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.


参考:LeetCode 216 Combination Sum III

这次是指定了元素的个数,用一个变量记录即可。

  1. public List<List<Integer>> combinationSum3(int k, int n) {
  2. List<List<Integer>> rt = new ArrayList<List<Integer>>();
  3. if (k < 1 || n < 1) {
  4. return rt;
  5. }
  6. List<Integer> cur = new ArrayList<Integer>();
  7. dfs(rt, cur, 0, k, n, 1);
  8. return rt;
  9. }
  10. private void dfs(List<List<Integer>> rt, List<Integer> cur, int sum, int k,
  11. int n, int level) {
  12. if (sum == n && k == 0) {
  13. rt.add(new ArrayList<Integer>(cur));
  14. return;
  15. } else if (sum > n || k <= 0) {
  16. return;
  17. }
  18. for (int i = level; i <= 9; i++) {
  19. cur.add(i);
  20. dfs(rt, cur, sum + i, k - 1, n, i + 1);
  21. cur.remove(cur.size() - 1);
  22. }
  23. }

Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.


参考:LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal

题目要求:根据前序遍历和中序遍历序列,构建二叉树。

前序遍历p[0]是二叉树的根结点,1是i[2],则:

  1. int p = 0;
  2. int[] preorder;
  3. int[] inorder;
  4. public TreeNode buildTree(int[] preorder, int[] inorder) {
  5. this.preorder = preorder;
  6. this.inorder = inorder;
  7. return buildTree(0, preorder.length);
  8. }
  9. TreeNode buildTree(int start, int end) {
  10. if (start >= end) {
  11. return null;
  12. }
  13. TreeNode root = new TreeNode(preorder[p]);
  14. int i;
  15. for (i = start; i < end && preorder[p] != inorder[i]; i++)
  16. ;
  17. p++;
  18. root.left = buildTree(start, i);
  19. root.right = buildTree(i + 1, end);
  20. return root;
  21. }

Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.


参考:LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal

  1. int p;
  2. int[] postorder;
  3. int[] inorder;
  4. public TreeNode buildTree(int[] inorder, int[] postorder) {
  5. this.p = postorder.length - 1;
  6. this.inorder = inorder;
  7. this.postorder = postorder;
  8. return buildTree(0, postorder.length);
  9. }
  10. TreeNode buildTree(int start, int end) {
  11. if (start >= end) {
  12. return null;
  13. }
  14. TreeNode root = new TreeNode(postorder[p]);
  15. int i;
  16. for (i = start; i < end && postorder[p] != inorder[i]; i++)
  17. ;
  18. p--;
  19. root.right = buildTree(i + 1, end);
  20. root.left = buildTree(start, i);
  21. return root;
  22. }

Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.


参考:LeetCode 217 Contains Duplicate

  1. public boolean containsDuplicate(int[] nums) {
  2. Set<Integer> s = new HashSet<Integer>();
  3. for (int n : nums) {
  4. if (s.contains(n)) {
  5. return true;
  6. }
  7. s.add(n);
  8. }
  9. return false;
  10. }

Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.


参考:LeetCode 219 Contains Duplicate II

建立一个map,key是出现过的元素,value是该元素的下标。若相同元素距离大于k,则更新下标。

  1. public boolean containsNearbyDuplicate(int[] nums, int k) {
  2. Map<Integer, Integer> map = new HashMap<Integer, Integer>();
  3. for (int i = 0; i < nums.length; i++) {
  4. if (map.containsKey(nums[i])) {
  5. if (i - map.get(nums[i]) <= k) {
  6. return true;
  7. }
  8. }
  9. map.put(nums[i], i);
  10. }
  11. return false;
  12. }

Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.


参考:LeetCode 220 Contains Duplicate III

对于加入的元素,要能够在O(1)时间内查找,同时还要自动排序,维持一个k个元素的TreeSet。

  1. public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
  2. if (k < 1 || t < 0 || nums == null || nums.length < 2) {
  3. return false;
  4. }
  5. SortedSet<Long> set = new TreeSet<Long>();
  6. for (int j = 0; j < nums.length; j++) {
  7. SortedSet<Long> subSet = set.subSet((long) nums[j] - t,
  8. (long) nums[j] + t + 1);
  9. // 集合不为空,则表示找到解
  10. if (!subSet.isEmpty()) {
  11. return true;
  12. }
  13. if (j >= k) {
  14. set.remove((long) nums[j - k]);
  15. }
  16. set.add((long) nums[j]);
  17. }
  18. return false;
  19. }

Find Minimum in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array.


参考:LeetCode 153 Find Minimum in Rotated Sorted Array

数列基本有序,则使用二分查找。假设数列是n,s是起始下标,e是最后下标,m是中间元素下标。分为三种情况:

  1. n[s] < n[e]
  2. n[m] > n[s] > n[e]
  3. n[m] < n[e] < n[s]

情况1:n[s] < n[e]

0 1 2 4 5 6 7

这种情况,直接返回n[s]。因为数列是有序的,或者只是旋转过一次。如果n[s] < n[e],则表明没有旋转。最小元素是n[s]。

情况2:n[m] > n[s] > n[e]

4 5 6 7 0 1 2

只需要满足n[m] > n[s]即可,因为第一种情况排除后,n[s]就一定会 > n[e]。

在本例中:

  1. n[s] = 4
  2. n[m] = 7
  3. n[e] = 2

则最小值肯定在7之后,到2之间,即 [m+1, e]。

情况3:n[m] < n[e] < n[s]

6 7 0 1 2 4 5

n[m] < n[e],在本例中:

  1. n[s] = 6
  2. n[m] = 1
  3. n[e] = 5

则表明,从m到e,数组已经是上升的,所以最小值在[s, m]。

  1. public int findMin(int[] nums) {
  2. if (nums.length == 1) {
  3. return nums[0];
  4. }
  5. if (nums.length == 2) {
  6. return Math.min(nums[0], nums[1]);
  7. }
  8. int s = 0, e = nums.length - 1;
  9. int m = (s + e) / 2;
  10. if (nums[s] < nums[e]) {
  11. return nums[s];
  12. }
  13. if (nums[m] > nums[s]) {
  14. return findMin(Arrays.copyOfRange(nums, m + 1, e + 1));
  15. }
  16. return findMin(Arrays.copyOfRange(nums, s, m + 1));
  17. }

Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

Note:

Your solution should be in logarithmic complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


参考:LeetCode 162 Find Peak Element

  1. public int findPeakElement(int[] nums) {
  2. int low = 0;
  3. int high = nums.length - 1;
  4. while (low < high) {
  5. int mid = low + (high - low) / 2;
  6. if (nums[mid] > nums[mid + 1]) {
  7. high = mid;
  8. } else {
  9. low = mid + 1;
  10. }
  11. }
  12. return low;
  13. }

Game of Life

According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Write a function to compute the next state (after one update) of the board given its current state.

Follow up:

  1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
  2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


参考:LeetCode 289 Game of Life

题目中说最好是in-place,因为board是int型的,所以要区分四种状态(dead是0,live是1):

  1. dead->live 01
  2. dead->dead 00
  3. live->dead 10
  4. live->live 11

或者直接用0,1,2,3四个数字表示四种状态都可以,然后通过移位进行结果的更新。

下面的图片,是一个Game of Life变化图。

这里写图片描述

  1. public void gameOfLife(int[][] board) {
  2. if (board == null || board.length == 0 || board[0] == null
  3. || board[0].length == 0)
  4. return;
  5. int m = board.length;
  6. int n = board[0].length;
  7. // 判断每个点,下一时刻的状态
  8. for (int i = 0; i < m; i++) {
  9. for (int j = 0; j < n; j++) {
  10. int x = getLiveNum(board, i, j);
  11. if (board[i][j] == 0) {
  12. if (x == 3)
  13. board[i][j] += 10;
  14. } else {
  15. if (x == 2 || x == 3)
  16. board[i][j] += 10;
  17. }
  18. }
  19. }
  20. // 更新每个点的状态
  21. for (int i = 0; i < m; i++) {
  22. for (int j = 0; j < n; j++) {
  23. board[i][j] /= 10;
  24. }
  25. }
  26. }
  27. // 获取board[x][y]邻居live的数量
  28. private int getLiveNum(int[][] board, int x, int y) {
  29. int c = 0;
  30. for (int i = x - 1; i <= x + 1; i++) {
  31. for (int j = y - 1; j <= y + 1; j++) {
  32. if (i < 0 || j < 0 || i > board.length - 1
  33. || j > board[0].length - 1 || (i == x && j == y))
  34. continue;
  35. if (board[i][j] % 10 == 1)
  36. c++;
  37. }
  38. }
  39. return c;
  40. }

Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:

A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.


参考:LeetCode 055 Jump Game

设变量maxStep为当前能够跳跃的最大步数,超过数组长度,就表示能够跳出;否则不能跳出。

那么maxStep怎么求得呢?nums[i] + i 就代表:从当前位置起跳,所能跳跃的最远位置

  1. public boolean canJump(int[] nums) {
  2. if (nums == null || nums.length == 0) {
  3. return false;
  4. }
  5. int maxStep = 0;
  6. for (int i = 0; i < nums.length; i++) {
  7. if (maxStep >= nums.length - 1) {
  8. return true;
  9. }
  10. if (nums[i] == 0 && maxStep == i) {
  11. return false;
  12. }
  13. maxStep = Math.max(maxStep, nums[i] + i);
  14. }
  15. return true;
  16. }

Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


参考:LeetCode 169 Majority Element

A Linear Time Majority Vote Algorithm 一个典型的算法,可以在一次遍历,时间复杂度是O(1),空间复杂度是O(1)的情况下完成。

  1. public int majorityElement(int[] nums) {
  2. int m = nums[0];
  3. int c = 1;
  4. for (int i = 1; i < nums.length; i++) {
  5. if (m == nums[i]) {
  6. c++;
  7. } else if (c > 1) {
  8. c--;
  9. } else {
  10. m = nums[i];
  11. }
  12. }
  13. return m;
  14. }

Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Hint:

  1. How many majority elements could it possibly have?
  2. Do you have a better hint? Suggest it!

参考:LeetCode 229 Majority Element II

因为题目中说是大于⌊ n/3 ⌋次数的元素,这样的元素最多只能有2个。

  1. public List<Integer> majorityElement(int[] nums) {
  2. List<Integer> rt = new ArrayList<Integer>();
  3. if (nums == null || nums.length == 0) {
  4. return rt;
  5. }
  6. int m1 = nums[0];
  7. int m2 = 0;
  8. int c1 = 1;
  9. int c2 = 0;
  10. for (int i = 1; i < nums.length; i++) {
  11. int x = nums[i];
  12. if (x == m1) {
  13. c1++;
  14. } else if (x == m2) {
  15. c2++;
  16. } else if (c1 == 0) {
  17. m1 = x;
  18. c1 = 1;
  19. } else if (c2 == 0) {
  20. m2 = x;
  21. c2 = 1;
  22. } else {
  23. c1--;
  24. c2--;
  25. }
  26. }
  27. c1 = 0;
  28. c2 = 0;
  29. for (int i = 0; i < nums.length; i++) {
  30. if (m1 == nums[i]) {
  31. c1++;
  32. } else if (m2 == nums[i]) {
  33. c2++;
  34. }
  35. }
  36. if (c1 > nums.length / 3) {
  37. rt.add(m1);
  38. }
  39. if (c2 > nums.length / 3) {
  40. rt.add(m2);
  41. }
  42. return rt;
  43. }

Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.


参考:LeetCode 053 Maximum Subarray

curSum存储数组当前的和,maxSum存储数组中连续最大的和。

假设数组是[−2,1,−3,4,−1,2,1,−5,4],首先curSum = -2, maxSum = -2。

  1. 当i=1时,对于数组[-2,1],curSum + nums[1] = -1, 小于nums[1] = 1。所以以后-2就可以舍弃,计算curSum时就从i=1开始。
  2. 当i=2时,对于数组[-2,1,-3],curSum + nums[2] = -2, 大于nums[2] = -3。虽然没有比原来大,但是至少比nums[2]大,对于以后计算更接近最优解。
  3. 以此类推。

本题只是返回连续最大和,并没有返回数组,所以没有必要记录下标。curSum和maxSum 的计算公式如下:

  1. public int maxSubArray(int[] nums) {
  2. if (nums == null || nums.length == 0) {
  3. return 0;
  4. }
  5. int curSum = nums[0];
  6. int maxSum = nums[0];
  7. for (int i = 1; i < nums.length; i++) {
  8. curSum = Math.max(curSum + nums[i], nums[i]);
  9. maxSum = Math.max(curSum, maxSum);
  10. }
  11. return maxSum;
  12. }

Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.


参考:LeetCode 152 Maximum Product Subarray

LeetCode第53题Maximum Subarray是求连续和最大的子数组,本题是求连续乘积最大的子数组。

在解法上是一样的,只是在求和时,是负就舍弃。但是在乘积中,因为负数*负数=正数,所以连续乘积为负数时,并不能舍弃这个数,因为如果数组的元素是负数,它可能成为乘积最大的数。

所以LeetCode第53题Maximum Subarray,只需要定义一个变量,用来记录和;本题要定义两个变量:positive和negative,分别记录当前乘积最大值和最小值。

  1. public int maxProduct(int[] nums) {
  2. int max = nums[0];
  3. int positive = nums[0];
  4. int negative = nums[0];
  5. for (int i = 1; i < nums.length; i++) {
  6. positive *= nums[i];
  7. negative *= nums[i];
  8. if (positive < negative) {
  9. int t = positive;
  10. positive = negative;
  11. negative = t;
  12. }
  13. positive = Math.max(positive, nums[i]);
  14. negative = Math.min(negative, nums[i]);
  15. max = Math.max(max, positive);
  16. }
  17. return max;
  18. }

Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.


参考:LeetCode 088 Merge Sorted Array

  1. public int help(int[] nums, int k) {
  2. if (k < 0) {
  3. return Integer.MIN_VALUE;
  4. }
  5. return nums[k];
  6. }
  7. public void merge(int[] nums1, int m, int[] nums2, int n) {
  8. if (nums1 == null || nums2 == null) {
  9. return;
  10. }
  11. int t = m + n - 1;
  12. while (t >= 0) {
  13. int n1 = help(nums1, m - 1);
  14. int n2 = help(nums2, n - 1);
  15. if (n1 > n2) {
  16. nums1[t] = n1;
  17. m--;
  18. } else {
  19. nums1[t] = n2;
  20. n--;
  21. }
  22. t--;
  23. }
  24. }

Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.


参考:LeetCode 064 Minimum Path Sum

建立一个背包dp[m][n],其中dp[i][j]表示从grid[0][0]到grid[i][j]的最小和。

  1. public int minPathSum(int[][] grid) {
  2. if (grid == null || grid[0] == null) {
  3. return 0;
  4. }
  5. int m = grid.length;
  6. int n = grid[0].length;
  7. int[][] dp = new int[m][n];
  8. dp[0][0] = grid[0][0];
  9. for (int y = 1; y < n; y++) {
  10. dp[0][y] = dp[0][y - 1] + grid[0][y];
  11. }
  12. for (int x = 1; x < m; x++) {
  13. dp[x][0] = dp[x - 1][0] + grid[x][0];
  14. }
  15. for (int y = 1; y < n; y++) {
  16. for (int x = 1; x < m; x++) {
  17. int min = Math.min(dp[x - 1][y], dp[x][y - 1]);
  18. dp[x][y] = min + grid[x][y];
  19. }
  20. }
  21. return dp[m - 1][n - 1];
  22. }

Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

More practice:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.


参考:LeetCode 209 Minimum Size Subarray Sum

定义两个指针,st和ed。如果sum>=s,sum从前面元素开始减;如果sum< s,ed++。

  1. public int minSubArrayLen(int s, int[] nums) {
  2. int sum = 0;
  3. int st = 0;
  4. int min = Integer.MAX_VALUE;
  5. for (int i = 0; i < nums.length; i++) {
  6. sum += nums[i];
  7. if (sum >= s) {
  8. while (sum - nums[st] >= s) {
  9. sum -= nums[st++];
  10. }
  11. min = Math.min(min, i - st + 1);
  12. }
  13. }
  14. if (min > nums.length) {
  15. return 0;
  16. }
  17. return min;
  18. }

Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


参考:LeetCode 268 Missing Number

既然是0~n只差其中一个数,不如再次加入0~n的序列,这样就和LeetCode 136 Single Number一样了,missing number只出现一次,其余都是出现两次。

  1. public int missingNumber(int[] nums) {
  2. int rt = nums.length;
  3. for (int i = 0; i < nums.length; i++) {
  4. rt = rt ^ nums[i] ^ i;
  5. }
  6. return rt;
  7. }

Move Zeroes

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


参考:LeetCode 283 Move Zeroes

  1. public void moveZeroes(int[] nums) {
  2. int t = 0;
  3. // 把非0元素移到前面
  4. for (int i = 0; i < nums.length; i++) {
  5. if (nums[i] != 0) {
  6. nums[t++] = nums[i];
  7. }
  8. }
  9. // 把后面元素值0
  10. for (int i = t; i < nums.length; i++) {
  11. nums[i] = 0;
  12. }
  13. }

Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1


参考:LeetCode 031 Next Permutation

  1. public void nextPermutation(int[] nums) {
  2. if (nums == null || nums.length < 2) {
  3. return;
  4. }
  5. int p = 0;
  6. for (int i = nums.length - 2; i >= 0; i--) {
  7. if (nums[i] < nums[i + 1]) {
  8. p = i;
  9. break;
  10. }
  11. }
  12. int q = 0;
  13. for (int i = nums.length - 1; i > p; i--) {
  14. if (nums[i] > nums[p]) {
  15. q = i;
  16. break;
  17. }
  18. }
  19. if (p == 0 && q == 0) {
  20. reverse(nums, 0, nums.length - 1);
  21. return;
  22. }
  23. int temp = nums[p];
  24. nums[p] = nums[q];
  25. nums[q] = temp;
  26. if (p < nums.length - 1) {
  27. reverse(nums, p + 1, nums.length - 1);
  28. }
  29. }
  30. private void reverse(int[] nums, int left, int right) {
  31. while (left < right) {
  32. int temp = nums[left];
  33. nums[left] = nums[right];
  34. nums[right] = temp;
  35. left++;
  36. right--;
  37. }
  38. }

Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

参考:LeetCode 118 Pascal's Triangle

  1. public List<List<Integer>> generate(int numRows) {
  2. ArrayList<List<Integer>> rt = new ArrayList<List<Integer>>();
  3. Integer[] pre = null;
  4. for (int i = 1; i <= numRows; i++) {
  5. //must be defined as Integer[]
  6. Integer[] row = new Integer[i];
  7. row[0] = 1;
  8. row[i - 1] = 1;
  9. for (int j = 1; j < i - 1; j++) {
  10. row[j] = pre[j] + pre[j - 1];
  11. }
  12. rt.add(new ArrayList<Integer>(Arrays.asList(row)));
  13. pre = row;
  14. }
  15. return rt;
  16. }

Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?


参考:LeetCode 119 Pascal's Triangle II

  1. public List<Integer> getRow(int rowIndex) {
  2. Integer[] row = new Integer[rowIndex + 1];
  3. Arrays.fill(row, 1);
  4. for (int i = 0; i < rowIndex - 1; i++) {
  5. for (int j = i + 1; j >= 1; j--) {
  6. row[j] = row[j] + row[j - 1];
  7. }
  8. }
  9. return Arrays.asList(row);
  10. }

Plus One

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.


参考:LeetCode 066 Plus One

  1. public int[] plusOne(int[] digits) {
  2. if (digits == null || digits.length == 0) {
  3. return null;
  4. }
  5. int[] rt = new int[digits.length + 1];
  6. digits[digits.length - 1]++;
  7. for (int i = digits.length - 1; i >= 0; i--) {
  8. rt[i + 1] += digits[i];
  9. rt[i] += rt[i + 1] / 10;
  10. rt[i + 1] %= 10;
  11. }
  12. if (rt[0] == 0) {
  13. return Arrays.copyOfRange(rt, 1, rt.length);
  14. } else {
  15. return rt;
  16. }
  17. }

Product of Array Except Self

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)


参考:LeetCode 238 Product of Array Except Self

可以定义两个辅助数组,left和right。

left[i]:存放nums[i]之前的乘积
right[i]:存放nums[i]之后的乘积

但是分析一下,空间可以优化,因为我们先从右向左算,再从左向右算,只需要返回的那一个数组就够了。

  1. public int[] productExceptSelf(int[] nums) {
  2. int[] rt = new int[nums.length];
  3. rt[nums.length - 1] = 1;
  4. for (int i = nums.length - 2; i >= 0; i--) {
  5. rt[i] = rt[i + 1] * nums[i+1];
  6. }
  7. int left = 1;
  8. for (int i = 0; i < nums.length; i++) {
  9. rt[i] *= left;
  10. left *= nums[i];
  11. }
  12. return rt;
  13. }

Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.


参考:LeetCode 026 Remove Duplicates from Sorted Array

  1. public int removeDuplicates(int[] nums) {
  2. if (nums == null) {
  3. return -1;
  4. }
  5. if (nums.length < 2) {
  6. return nums.length;
  7. }
  8. int len = 0;
  9. for (int i = 1; i < nums.length; i++) {
  10. if (nums[len] != nums[i]) {
  11. nums[++len] = nums[i];
  12. }
  13. }
  14. return len + 1;
  15. }

Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.


参考:LeetCode 080 Remove Duplicates from Sorted Array II

  1. public int removeDuplicates(int[] nums) {
  2. int cur = 2;
  3. for (int i = cur; i < nums.length; i++) {
  4. // 一个数字,最多出现2次
  5. if (!(nums[i] == nums[cur - 1] && nums[i] == nums[cur - 2])) {
  6. nums[cur++] = nums[i];
  7. }
  8. }
  9. return Math.min(cur, nums.length);
  10. }

Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.


参考:LeetCode 027 Remove Element

  1. public int removeElement(int[] nums, int val) {
  2. if (nums == null || nums.length == 0) {
  3. return 0;
  4. }
  5. int len = 0;
  6. for (int i = 0; i < nums.length; i++) {
  7. if (nums[i] != val) {
  8. nums[len++] = nums[i];
  9. }
  10. }
  11. return len;
  12. }

Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

[show hint]

Hint:
Could you do it in-place with O(1) extra space?

Related problem: Reverse Words in a String II

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.


参考:LeetCode 189 Rotate Array

  1. void reverse(int[] nums, int st, int ed) {
  2. while (st < ed) {
  3. int t = nums[st];
  4. nums[st] = nums[ed];
  5. nums[ed] = t;
  6. st++;
  7. ed--;
  8. }
  9. }
  10. public void rotate(int[] nums, int k) {
  11. int length = nums.length;
  12. k = k % length;
  13. if (length == 1 || k == 0)
  14. return;
  15. reverse(nums, 0, length - k - 1);
  16. reverse(nums, length - k, length - 1);
  17. reverse(nums, 0, length - 1);
  18. }

Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?


参考:LeetCode 048 Rotate Image

这里写图片描述

  1. public void rotate(int[][] matrix) {
  2. if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
  3. return;
  4. }
  5. final int mx = matrix.length;
  6. final int my = matrix[0].length;
  7. int x, y;
  8. int t;
  9. int _my = my - 1;
  10. for (x = 0; x < mx - 1; x++) {
  11. for (y = 0; y < _my; y++) {
  12. int ny = mx - 1 - x;
  13. int nx = my - 1 - y;
  14. t = matrix[y][x];
  15. matrix[y][x] = matrix[ny][nx];
  16. matrix[ny][nx] = t;
  17. }
  18. _my--;
  19. }
  20. for (x = 0; x < mx; x++) {
  21. for (y = 0; y < my / 2; y++) {
  22. int ny = my - 1 - y;
  23. int nx = x;
  24. t = matrix[y][x];
  25. matrix[y][x] = matrix[ny][nx];
  26. matrix[ny][nx] = t;
  27. }
  28. }
  29. }

Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.


参考:LeetCode 074 Search a 2D Matrix

  1. public boolean searchMatrix(int[][] matrix, int target) {
  2. int mx = matrix.length;
  3. int my = matrix[0].length;
  4. int l = 0;
  5. int r = mx * my;
  6. while (l < r) {
  7. int m = l + (r - l) / 2;
  8. // 将m转换成x、y
  9. int x = m / my;
  10. int y = m % my;
  11. // 二分查找:matrix[x][y]转换成一维数组,坐标就是m
  12. if (matrix[x][y] == target) {
  13. return true;
  14. } else if (matrix[x][y] < target) {
  15. l = m + 1;
  16. } else {
  17. r = m;
  18. }
  19. }
  20. return false;
  21. }

Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].


参考:LeetCode 034 Search for a Range

  1. public int[] searchRange(int[] nums, int target) {
  2. int l = 0, r = nums.length;
  3. while (l < r) {
  4. int m = l + (r - l) / 2;
  5. if (nums[m] == target) {
  6. int s = m, e = m;
  7. while (s - 1 >= 0 && nums[s - 1] == target) {
  8. s--;
  9. }
  10. while (e + 1 < nums.length && nums[e + 1] == target) {
  11. e++;
  12. }
  13. return new int[] { s, e };
  14. } else if (nums[m] > target) {
  15. r = m;
  16. } else {
  17. l = m + 1;
  18. }
  19. }
  20. return new int[] { -1, -1 };
  21. }

Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.


参考:LeetCode 033 Search in Rotated Sorted Array

  1. public int search(int[] nums, int target) {
  2. int l = 0, r = nums.length - 1;
  3. while (l <= r) {
  4. int m = (l + r) / 2;
  5. if (nums[m] == target)
  6. return m;
  7. if (nums[l] < nums[m]) {
  8. if (target <= nums[m] && target >= nums[l])
  9. r = m - 1;
  10. else
  11. l = m + 1;
  12. } else if (nums[l] > nums[m]) {
  13. if (target >= nums[l] || target <= nums[m])
  14. r = m - 1;
  15. else
  16. l = m + 1;
  17. } else
  18. l++;
  19. }
  20. return -1;
  21. }

Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.


参考:LeetCode 081 Search in Rotated Sorted Array II

  1. public boolean search(int[] nums, int target) {
  2. int l = 0, r = nums.length - 1;
  3. while (l <= r) {
  4. int m = (l + r) / 2;
  5. if (nums[m] == target)
  6. return true;
  7. if (nums[l] < nums[m]) {
  8. if (target <= nums[m] && target >= nums[l])
  9. r = m - 1;
  10. else
  11. l = m + 1;
  12. } else if (nums[l] > nums[m]) {
  13. if (target >= nums[l] || target <= nums[m])
  14. r = m - 1;
  15. else
  16. l = m + 1;
  17. } else
  18. l++;
  19. }
  20. return false;
  21. }

Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0


参考:LeetCode 035 Search Insert Position

  1. public int searchInsert(int[] nums, int target) {
  2. if (nums == null || nums.length == 0) {
  3. return 0;
  4. }
  5. for (int i = 0; i < nums.length; i++) {
  6. if (target <= nums[i]) {
  7. return i;
  8. }
  9. }
  10. return nums.length;
  11. }

Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

click to show follow up.

Follow up:

Did you use extra space?
A straight forward solution using O(_m__n_) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?


参考:LeetCode 073 Set Matrix Zeroes

  1. public void setZeroes(int[][] matrix) {
  2. if (matrix == null || matrix.length == 0) {
  3. return;
  4. }
  5. int mx = matrix.length;
  6. int my = matrix[0].length;
  7. // 两个变量,判断第一行和第一列是否有0
  8. boolean xflag = false, yflag = false;
  9. // 判断第一行是否有0
  10. for (int i = 0; i < mx; i++) {
  11. if (matrix[i][0] == 0) {
  12. xflag = true;
  13. break;
  14. }
  15. }
  16. // 判断第一列是否有0
  17. for (int i = 0; i < my; i++) {
  18. if (matrix[0][i] == 0) {
  19. yflag = true;
  20. break;
  21. }
  22. }
  23. // 其它行、列是否有0
  24. for (int i = 1; i < mx; i++) {
  25. for (int j = 1; j < my; j++) {
  26. if (matrix[i][j] == 0) {
  27. matrix[i][0] = 0;
  28. matrix[0][j] = 0;
  29. }
  30. }
  31. }
  32. // 对于第一列,为0,则将所在行变成0
  33. for (int i = 1; i < mx; i++) {
  34. if (matrix[i][0] == 0) {
  35. for (int j = 0; j < my; j++) {
  36. matrix[i][j] = 0;
  37. }
  38. }
  39. }
  40. // 对于第一行,为0,则将所在列变成0
  41. for (int i = 0; i < my; i++) {
  42. if (matrix[0][i] == 0) {
  43. for (int j = 0; j < mx; j++) {
  44. matrix[j][i] = 0;
  45. }
  46. }
  47. }
  48. // 若原来第一行中有0,则将整行置0
  49. if (xflag) {
  50. for (int i = 0; i < mx; i++) {
  51. matrix[i][0] = 0;
  52. }
  53. }
  54. // 若原来第一列中有0,则将整列置0
  55. if (yflag) {
  56. for (int i = 0; i < my; i++) {
  57. matrix[0][i] = 0;
  58. }
  59. }
  60. }

Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note:
You are not suppose to use the library's sort function for this problem.

click to show follow up.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?


参考:LeetCode 075 Sort Colors

  1. public void sortColors(int[] nums) {
  2. if (nums == null || nums.length == 0) {
  3. return;
  4. }
  5. // 定义三个变量,存储三种颜色出现次数
  6. int red = 0;
  7. int white = 0;
  8. int blue = 0;
  9. // 循环一次,记录每种颜色出现次数
  10. for (int i = 0; i < nums.length; i++) {
  11. if (nums[i] == 0) {
  12. red++;
  13. } else if (nums[i] == 1) {
  14. white++;
  15. } else {
  16. blue++;
  17. }
  18. }
  19. // 对nums数组重新赋值
  20. int i = 0;
  21. while (red-- > 0) {
  22. nums[i++] = 0;
  23. }
  24. while (white-- > 0) {
  25. nums[i++] = 1;
  26. }
  27. while (blue-- > 0) {
  28. nums[i++] = 2;
  29. }
  30. }

Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].


参考:LeetCode 054 Spiral Matrix

  1. public List<Integer> spiralOrder(int[][] matrix) {
  2. List<Integer> rt = new ArrayList<Integer>();
  3. if (matrix == null || matrix.length == 0) {
  4. return rt;
  5. }
  6. int startx = 0, endx = matrix.length - 1;
  7. int starty = 0, endy = matrix[0].length - 1;
  8. while (startx <= endx && starty <= endy) {
  9. // 上边的行,从左向右
  10. for (int y = starty; y <= endy; y++) {
  11. rt.add(matrix[startx][y]);
  12. }
  13. // 右边的列,从上到下
  14. for (int x = startx + 1; x <= endx; x++) {
  15. rt.add(matrix[x][endy]);
  16. }
  17. // 如果行或列遍历完,则退出循环
  18. if (startx == endx || starty == endy) {
  19. break;
  20. }
  21. // 下边的行,从右向左
  22. for (int y = endy - 1; y >= starty; y--) {
  23. rt.add(matrix[endx][y]);
  24. }
  25. // 左边的列,从下到上
  26. for (int x = endx - 1; x >= startx + 1; x--) {
  27. rt.add(matrix[x][starty]);
  28. }
  29. startx++;
  30. starty++;
  31. endx--;
  32. endy--;
  33. }
  34. return rt;
  35. }

Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

参考:LeetCode 059 Spiral Matrix II

  1. public int[][] generateMatrix(int n) {
  2. if (n <= 0) {
  3. return new int[0][0];
  4. }
  5. int[][] matrix = new int[n][n];
  6. int num = 1;
  7. int startx = 0, endx = n - 1;
  8. int starty = 0, endy = n - 1;
  9. while (startx <= endx && starty <= endy) {
  10. // 上边的行,从左向右
  11. for (int y = starty; y <= endy; y++) {
  12. matrix[startx][y] = num++;
  13. }
  14. // 右边的列,从上到下
  15. for (int x = startx + 1; x <= endx; x++) {
  16. matrix[x][endy] = num++;
  17. }
  18. // 如果行或列遍历完,则退出循环
  19. if (startx == endx || starty == endy) {
  20. break;
  21. }
  22. // 下边的行,从右向左
  23. for (int y = endy - 1; y >= starty; y--) {
  24. matrix[endx][y] = num++;
  25. }
  26. // 左边的列,从下到上
  27. for (int x = endx - 1; x >= startx + 1; x--) {
  28. matrix[x][starty] = num++;
  29. }
  30. startx++;
  31. starty++;
  32. endx--;
  33. endy--;
  34. }
  35. return matrix;
  36. }

Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note:

For example,
If nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

参考:LeetCode 078 Subsets

  1. int target;// 次数
  2. Integer[] stack;// 存储每次排列
  3. List<List<Integer>> rt;// 存储结果
  4. public void search(int p, int[] nums) {
  5. // 若长度为k,则stack是其中一个结果,保存结果
  6. if (p == target) {
  7. rt.add(new ArrayList<Integer>(Arrays.asList(stack)));
  8. return;
  9. }
  10. for (int i = 0; i < nums.length; i++) {
  11. if (p > 0 && nums[i] <= stack[p - 1]) {
  12. continue;
  13. }
  14. stack[p] = nums[i];
  15. search(p + 1, nums);
  16. }
  17. }
  18. public List<List<Integer>> subsets(int[] nums) {
  19. Arrays.sort(nums);
  20. rt = new ArrayList<List<Integer>>();
  21. // 分别做0~num.length长度的组合
  22. for (int i = 0; i <= nums.length; i++) {
  23. target = i;
  24. stack = new Integer[i];
  25. search(0, nums);
  26. }
  27. return rt;
  28. }

Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note:

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

参考:LeetCode 090 Subsets II

使用二进制,不需要递归。对于二进制中的每一位,0表示不选择,1表示选择。则有2^n种情况。
使用HashSet,能够直接过滤重复情况(先对数组排序,题目中也要求每个list非降序排列)。

  1. public List<List<Integer>> subsetsWithDup(int[] nums) {
  2. if (nums == null) {
  3. return null;
  4. }
  5. if (nums.length == 0) {
  6. return new ArrayList<List<Integer>>();
  7. }
  8. Set<List<Integer>> set = new HashSet<List<Integer>>();
  9. // 题目中要求每个list是非降序,所以要先从小到大排序
  10. Arrays.sort(nums);
  11. // 对于n位,有2^n种情况
  12. for (int i = 0; i < Math.pow(2, nums.length); i++) {
  13. List<Integer> list = new ArrayList<Integer>();
  14. int tmp = i;
  15. // 对于每种情况,分别求得二进制中1的个数
  16. // 0代表不选择,1代表选择
  17. for (int j = 0; j < nums.length; j++) {
  18. int bit = tmp & 1;
  19. tmp >>= 1;
  20. if (bit == 1) {
  21. list.add(nums[j]);
  22. }
  23. }
  24. set.add(list);
  25. }
  26. return new ArrayList<List<Integer>>(set);
  27. }

Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


参考:LeetCode 228 Summary Ranges

  1. public List<String> summaryRanges(int[] nums) {
  2. List<String> rt = new ArrayList<String>();
  3. if (nums == null || nums.length == 0) {
  4. return rt;
  5. }
  6. for (int i = 0; i < nums.length; i++) {
  7. int st = nums[i];
  8. int ed = st;
  9. while (i + 1 < nums.length && nums[i + 1] - ed == 1) {
  10. i++;
  11. ed++;
  12. }
  13. if (ed == st) {
  14. rt.add(st + "");
  15. } else {
  16. rt.add(st + "->" + ed);
  17. }
  18. }
  19. return rt;
  20. }

Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.


参考:LeetCode 062 Unique Paths

构造二维数组dp[m][n],其中:

  1. public int uniquePaths(int m, int n) {
  2. if (m <= 0 || n <= 0) {
  3. return 0;
  4. }
  5. int[][] dp = new int[m][n];
  6. for (int y = 1; y < n; y++) {
  7. dp[0][y] = 1;
  8. }
  9. for (int x = 1; x < m; x++) {
  10. dp[x][0] = 1;
  11. }
  12. for (int y = 1; y < n; y++) {
  13. for (int x = 1; x < m; x++) {
  14. dp[x][y] = dp[x - 1][y] + dp[x][y - 1];
  15. }
  16. }
  17. return dp[m - 1][n - 1];
  18. }

Unique Paths II

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,

There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is 2.

Note: m and n will be at most 100.


参考:LeetCode 063 Unique Paths II

和上一题一样,只是有障碍物的时候(obstacleGrid[i][j]==1),将对应的dp置0(dp[i][j]=0)

  1. public int uniquePathsWithObstacles(int[][] obstacleGrid) {
  2. if (obstacleGrid == null || obstacleGrid[0] == null) {
  3. return 0;
  4. }
  5. if (obstacleGrid[0][0] == 1) {
  6. return 0;
  7. }
  8. int m = obstacleGrid.length;
  9. int n = obstacleGrid[0].length;
  10. int[][] dp = new int[m][n];
  11. for (int y = 1; y < n; y++) {
  12. if (obstacleGrid[0][y] == 0) {
  13. dp[0][y] = 1;
  14. } else {
  15. break;
  16. }
  17. }
  18. for (int x = 1; x < m; x++) {
  19. if (obstacleGrid[x][0] == 0) {
  20. dp[x][0] = 1;
  21. } else {
  22. break;
  23. }
  24. }
  25. for (int y = 1; y < n; y++) {
  26. for (int x = 1; x < m; x++) {
  27. if (obstacleGrid[x][y] == 1) {
  28. dp[x][y] = 0;
  29. } else {
  30. dp[x][y] = dp[x - 1][y] + dp[x][y - 1];
  31. }
  32. }
  33. }
  34. return dp[m - 1][n - 1];
  35. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注