[关闭]
@Yano 2019-09-20T10:50:56.000000Z 字数 58138 阅读 11760

LeetCode Array 题目汇总(前500题)

LeetCode


公众号

coding 笔记、点滴记录,以后的文章也会同步到公众号(Coding Insight)中,希望大家关注^_^

https://github.com/LjyYano/Thinking_in_Java_MindMapping

1 Two Sum

https://leetcode.com/problems/two-sum/

题目描述

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

代码

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

167 Two Sum II - Input array is sorted

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

题目描述

Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.

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

代码

  1. class Solution {
  2. public int[] twoSum(int[] nums, int target) {
  3. if (nums == null || nums.length < 2)
  4. return null;
  5. int start = 0, end = nums.length - 1;
  6. while(start < end) {
  7. int sum = nums[start] + nums[end];
  8. if(sum == target) return new int[]{start + 1, end + 1};
  9. else if(sum < target) start++;
  10. else end--;
  11. }
  12. return null;
  13. }
  14. }

15 3Sum

https://leetcode.com/problems/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: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:

[
  [-1, 0, 1],
  [-1, -1, 2]
]

代码

  1. class Solution {
  2. public List<List<Integer>> threeSum(int[] nums) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. if(nums == null || nums.length < 3) return ans;
  5. Set<List<Integer>> ansSet = new HashSet<>();
  6. Arrays.sort(nums);
  7. for(int l = 0; l <= nums.length - 3; l++) {
  8. // 起始位置与前一个值相同,结果不会更多
  9. if(l > 0 && nums[l] == nums[l - 1]) continue;
  10. int m = l + 1, r = nums.length - 1, sum = -nums[l];
  11. while(m < r) {
  12. if(nums[m] + nums[r] > sum) {
  13. r--;
  14. } else if(nums[m] + nums[r] < sum) {
  15. m++;
  16. } else {
  17. ansSet.add(Arrays.asList(nums[l], nums[m], nums[r]));
  18. m++;
  19. }
  20. }
  21. }
  22. ans.addAll(ansSet);
  23. return ans;
  24. }
  25. }

16 3Sum Closest

https://leetcode.com/problems/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).

代码

  1. class Solution {
  2. public int threeSumClosest(int[] nums, int target) {
  3. if(nums == null || nums.length < 3) return 0;
  4. Arrays.sort(nums);
  5. int minGap = Integer.MAX_VALUE;
  6. int ans = 0;
  7. for(int l = 0; l <= nums.length - 3; l++) {
  8. // 起始位置与前一个值相同,结果不会更多
  9. if(l > 0 && nums[l] == nums[l - 1]) continue;
  10. for(int m = l + 1, r = nums.length - 1; m < r; ) {
  11. int sum = nums[l] + nums[m] + nums[r];
  12. int gap = Math.abs(target - sum);
  13. if(gap < minGap) {
  14. minGap = gap;
  15. ans = sum;
  16. }
  17. if(sum == target) {
  18. return target;
  19. } else if(sum > target) {
  20. r--;
  21. } else {
  22. m++;
  23. }
  24. }
  25. }
  26. return ans;
  27. }
  28. }

18 4Sum

https://leetcode.com/problems/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: The solution set must not contain duplicate quadruplets.

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]
]

代码

  1. class Solution {
  2. public List<List<Integer>> fourSum(int[] nums, int target) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. if (nums == null || nums.length < 4)
  5. return ans;
  6. Set<List<Integer>> ansSet = new HashSet<>();
  7. Arrays.sort(nums);
  8. for (int i0 = 0; i0 <= nums.length - 4; i0++) {
  9. // 结果不会更好
  10. if (i0 > 0 && nums[i0] == nums[i0 - 1])
  11. continue;
  12. for (int i1 = i0 + 1; i1 <= nums.length - 3; i1++) {
  13. int sum = target - nums[i0] - nums[i1];
  14. int i2 = i1 + 1, i3 = nums.length - 1;
  15. while (i2 < i3) {
  16. if (nums[i2] + nums[i3] > sum) {
  17. i3--;
  18. } else if (nums[i2] + nums[i3] < sum) {
  19. i2++;
  20. } else {
  21. ansSet.add(Arrays.asList(nums[i0], nums[i1], nums[i2], nums[i3]));
  22. i2++;
  23. }
  24. }
  25. }
  26. }
  27. ans.addAll(ansSet);
  28. return ans;
  29. }
  30. }

4 Median of Two Sorted Arrays

https://leetcode.com/problems/median-of-two-sorted-arrays/

题目描述

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

代码

  1. class Solution {
  2. public:
  3. double findMedianSortedArrays(int A[], int m, int B[], int n) {
  4. int total = m + n;
  5. if(total & 0x1) return find_kth(A, m, B, n, total / 2 + 1);
  6. else return (find_kth(A, m, B, n, total / 2)
  7. + find_kth(A, m, B, n, total / 2 + 1))/2.0;
  8. }
  9. private:
  10. static int find_kth(int A[], int m, int B[], int n, int k){
  11. //always assume that m is equal or smaller than n
  12. if(m > n) return find_kth(B, n, A, m, k);
  13. if(m == 0) return B[k-1];
  14. if(k == 1) return min(A[0], B[0]);
  15. //divide k into two parts
  16. int ia = min(k / 2, m), ib = k - ia;
  17. if (A[ia - 1] < B[ib - 1])
  18. return find_kth(A + ia, m - ia, B, n, k - ia);
  19. else if (A[ia - 1] > B[ib - 1])
  20. return find_kth(A, m, B + ib, n - ib, k - ib);
  21. else
  22. return A[ia - 1];
  23. }
  24. };

11 Container With Most Water

https://leetcode.com/problems/container-with-most-water/

题目描述

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

代码

  1. public class Solution {
  2. public int maxArea(int[] nums) {
  3. if(nums == null) return 0;
  4. int ans = 0, start = 0, end = nums.length - 1;
  5. while(start < end) {
  6. int height = Math.min(nums[start], nums[end]);
  7. ans = Math.max(ans, (end - start) * height);
  8. if(nums[start] < nums[end]) {
  9. // 没有必要判断start 与右边的桶了,因为短板在 start
  10. start++;
  11. } else {
  12. end--;
  13. }
  14. }
  15. return ans;
  16. }
  17. }

42 Trapping Rain Water

https://leetcode.com/problems/trapping-rain-water/

题目描述

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

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

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

代码

  1. class Solution {
  2. public int trap(int[] height) {
  3. if(height == null) return 0;
  4. int ans = 0, maxLeft = 0, maxRight = 0;
  5. int left = 0, right = height.length - 1;
  6. while(left < right) {
  7. // 左位置的左边的最高值,右位置的右边的最高值
  8. maxLeft = Math.max(maxLeft, height[left]);
  9. maxRight = Math.max(maxRight, height[right]);
  10. if(maxLeft < maxRight) {
  11. ans += maxLeft - height[left++];
  12. } else {
  13. ans += maxRight - height[right--];
  14. }
  15. }
  16. return ans;
  17. }
  18. }

26 Remove Duplicates from Sorted Array

https://leetcode.com/problems/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 by modifying the input array in-place with O(1) extra memory.

Example:

Given 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.

代码

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

80 Remove Duplicates from Sorted Array II

https://leetcode.com/problems/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.

代码

  1. class Solution {
  2. public int removeDuplicates(int[] nums) {
  3. if(nums == null || nums.length <= 2) return nums.length;
  4. int count = 1;
  5. for(int i = 2; i < nums.length; i++) {
  6. if(nums[i] != nums[count] || (nums[i] == nums[count] && nums[i] != nums[count - 1])) {
  7. nums[++count] = nums[i];
  8. }
  9. }
  10. return count + 1;
  11. }
  12. }

27 Remove Element

https://leetcode.com/problems/remove-element/

题目描述

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

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

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

Example:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

代码

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

31 Next Permutation

https://leetcode.com/problems/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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

代码

  1. class Solution {
  2. public void nextPermutation(int[] nums) {
  3. // 1. 向前找首个递减
  4. for (int i = nums.length - 2; i >= 0; i--) {
  5. if (nums[i] < nums[i + 1]) {
  6. int j = nums.length - 1;
  7. // 2. 向前找首个大于nums[i]的索引
  8. for (; j > i; j--) {
  9. if (nums[j] > nums[i]) {
  10. break;
  11. }
  12. }
  13. // 3. 交换两个值
  14. swap(nums, i, j);
  15. // 4. 交换后面所有
  16. reverseSwap(nums, i + 1, nums.length - 1);
  17. return;
  18. }
  19. }
  20. reverseSwap(nums, 0, nums.length - 1);
  21. }
  22. private void reverseSwap(int[] nums, int start, int end) {
  23. while (start < end) {
  24. swap(nums, start++, end--);
  25. }
  26. }
  27. private void swap(int[] nums, int i, int j) {
  28. int tmp = nums[i];
  29. nums[i] = nums[j];
  30. nums[j] = tmp;
  31. }
  32. }

39 Combination Sum

https://leetcode.com/problems/combination-sum/

题目描述

Given a set of candidate numbers (C) (without duplicates) 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:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.

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

[
  [7],
  [2, 2, 3]
]

代码

  1. class Solution {
  2. public List<List<Integer>> combinationSum(int[] n, int target) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. if(n == null || n.length == 0) return ans;
  5. Arrays.sort(n);
  6. robot(n, 0, target, ans, new ArrayList<Integer>());
  7. return ans;
  8. }
  9. private void robot(int[] n, int start, int left, List<List<Integer>> ans, List<Integer> tmp) {
  10. if(left == 0) {
  11. ans.add(new ArrayList<>(tmp));
  12. return;
  13. }
  14. for(int i = start; i < n.length; i++) {
  15. // 如果不符合条件,则循环后面可以省略
  16. if(left >= n[i]) {
  17. tmp.add(n[i]);
  18. robot(n, i, left - n[i], ans, tmp);
  19. tmp.remove(tmp.size() - 1);
  20. } else {
  21. break;
  22. }
  23. }
  24. }
  25. }

40 Combination Sum II

https://leetcode.com/problems/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:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.

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]
]

代码

  1. class Solution {
  2. public List<List<Integer>> combinationSum2(int[] n, int target) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. if(n == null || n.length == 0) return ans;
  5. Arrays.sort(n);
  6. Set<List<Integer>> ansSet = new HashSet<>();
  7. robot(n, 0, target, ansSet, new ArrayList<Integer>());
  8. ans.addAll(ansSet);
  9. return ans;
  10. }
  11. private void robot(int[] n, int start, int left, Set<List<Integer>> ansSet, List<Integer> tmp) {
  12. if(left == 0) {
  13. ansSet.add(new ArrayList<>(tmp));
  14. return;
  15. }
  16. for(int i = start; i < n.length; i++) {
  17. // 如果不符合条件,则循环后面可以省略
  18. if(left >= n[i]) {
  19. tmp.add(n[i]);
  20. robot(n, i + 1, left - n[i], ansSet, tmp);
  21. tmp.remove(tmp.size() - 1);
  22. } else {
  23. break;
  24. }
  25. }
  26. }
  27. }

216 Combination Sum III

https://leetcode.com/problems/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.

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.

代码

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

33 Search in Rotated Sorted Array

https://leetcode.com/problems/search-in-rotated-sorted-array/

题目描述

Suppose an array sorted in ascending order 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.

代码

  1. class Solution {
  2. public int search(int[] nums, int target) {
  3. if(nums == null) return -1;
  4. int start = 0, end = nums.length - 1;
  5. while(start <= end) {
  6. int mid = (start + end) / 2;
  7. if(nums[mid] == target) {
  8. return mid;
  9. }
  10. // 左序列连续递增
  11. if(nums[start] <= nums[mid]) {
  12. if(target >= nums[start] && target < nums[mid]) {
  13. end = mid - 1;
  14. } else {
  15. start = mid + 1;
  16. }
  17. }
  18. // 右序列连续递增
  19. if(nums[mid] <= nums[end]) {
  20. if(target > nums[mid] && target <= nums[end]) {
  21. start = mid + 1;
  22. } else {
  23. end = mid - 1;
  24. }
  25. }
  26. }
  27. return -1;
  28. }
  29. }

81 Search in Rotated Sorted Array II

https://leetcode.com/problems/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?

Suppose an array sorted in ascending order 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).

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

The array may contain duplicates.

代码

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

34 Search for a Range

https://leetcode.com/problems/search-for-a-range/

题目描述

Given an array of integers sorted in ascending order, 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].

代码

  1. class Solution {
  2. public int[] searchRange(int[] nums, int target) {
  3. if(nums == null) return new int[] {-1, -1};
  4. // 先找到一个位置
  5. int start = 0, end = nums.length - 1, ans = -1;
  6. while(start <= end) {
  7. int mid = (start + end) / 2;
  8. if(nums[mid] == target) {
  9. ans = mid;
  10. break;
  11. }
  12. if(nums[mid] < target) {
  13. start = mid + 1;
  14. } else {
  15. end = mid - 1;
  16. }
  17. }
  18. if(ans == -1) return new int[] {-1, -1};
  19. // 找起始点
  20. int s = ans, e = ans;
  21. while(s >= 0 && nums[s] == target) {
  22. s--;
  23. }
  24. while(e < nums.length && nums[e] == target) {
  25. e++;
  26. }
  27. return new int[] {s + 1, e - 1};
  28. }
  29. }

35 Search Insert Position

https://leetcode.com/problems/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.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 1:

Input: [1,3,5,6], 0
Output: 0

代码

  1. class Solution {
  2. public int searchInsert(int[] nums, int target) {
  3. if(nums == null) return 0;
  4. // 先找到一个位置
  5. int start = 0, end = nums.length - 1, ans = -1;
  6. while(start <= end) {
  7. int mid = (start + end) / 2;
  8. if(nums[mid] == target) {
  9. ans = mid;
  10. break;
  11. }
  12. if(nums[mid] < target) {
  13. start = mid + 1;
  14. } else {
  15. end = mid - 1;
  16. }
  17. }
  18. if(ans != -1) return ans;
  19. // start 和 end 已经包含了插入的信息
  20. return start > end ? start : end;
  21. }
  22. }

41 First Missing Positive

https://leetcode.com/problems/first-missing-positive/

题目描述

Given an unsorted integer array, find the first missing positive integer.

For example,

Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

Your algorithm should run in O(n) time and uses constant space.

代码

  1. class Solution {
  2. public int firstMissingPositive(int[] n) {
  3. if(n == null) return 0;
  4. for(int i = 0; i < n.length; i++) {
  5. while(n[i] > 0 && n[i] <= n.length && n[i] != n[n[i] - 1]) {
  6. swap(n, i, n[i] - 1);
  7. }
  8. }
  9. // 遍历,找出n[i] != i + 1的结果
  10. for(int i = 0; i < n.length; i++) {
  11. if(n[i] != i + 1) return i + 1;
  12. }
  13. return n.length + 1;
  14. }
  15. private void swap(int[] n, int a, int b) {
  16. int tmp = n[a];
  17. n[a] = n[b];
  18. n[b] = tmp;
  19. }
  20. }

55 Jump Game

https://leetcode.com/problems/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.

代码

  1. class Solution {
  2. public boolean canJump(int[] nums) {
  3. if(nums == null || nums.length <= 1) return true;
  4. // farest[i] 表示[0, i]能跳到的最远位置
  5. int[] farest = new int[nums.length];
  6. farest[0] = nums[0];
  7. for(int i = 1; i < nums.length; i++) {
  8. // 若前面断档,则后面无解
  9. if(farest[i - 1] == i - 1) break;
  10. farest[i] = Math.max(farest[i - 1], nums[i] + i);
  11. }
  12. return farest[nums.length - 1] != 0;
  13. }
  14. }

45 Jump Game II

https://leetcode.com/problems/jump-game-ii/

题目描述

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Note:
You can assume that you can always reach the last index.

代码

  1. public class Solution {
  2. public int jump(int[] nums) {
  3. if (nums.length <= 1) return 0;
  4. int reach = nums[0];
  5. int lastreach = 0;
  6. int step = 0;
  7. for (int i = 1; i <= reach && i < nums.length; i++) {
  8. if (i > lastreach) {
  9. step++;
  10. lastreach = reach;
  11. }
  12. reach = Math.max(reach, i + nums[i]);
  13. }
  14. if (reach < nums.length - 1) return 0;
  15. return step;
  16. }
  17. }

48 Rotate Image

https://leetcode.com/problems/rotate-image/

题目描述

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

Rotate the image by 90 degrees (clockwise).

Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Given input matrix =

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

rotate the input matrix in-place such that it becomes:

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

Example 2:

Given input matrix =

[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

rotate the input matrix in-place such that it becomes:

[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

代码

  1. class Solution {
  2. public void rotate(int[][] matrix) {
  3. if(matrix == null || matrix[0] == null || matrix.length != matrix[0].length) return;
  4. int n = matrix.length;
  5. // 中轴互换
  6. for(int i = 0; i < n / 2; i++) {
  7. for(int j = 0; j < n; j++) {
  8. swap(matrix, i, j, n - i - 1, j);
  9. }
  10. }
  11. // 正对角线互换
  12. for(int i = 0; i < n; i++) {
  13. for(int j = i + 1; j < n; j++) {
  14. swap(matrix, i, j, j, i);
  15. }
  16. }
  17. }
  18. private void swap(int[][] matrix, int x0, int y0, int x1, int y1) {
  19. int tmp = matrix[x0][y0];
  20. matrix[x0][y0] = matrix[x1][y1];
  21. matrix[x1][y1] = tmp;
  22. }
  23. }

53 Maximum Subarray

https://leetcode.com/problems/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.

click to show more practice.

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.

代码

  1. class Solution {
  2. public int maxSubArray(int[] nums) {
  3. if(nums == null) return 0;
  4. // 数组可省略
  5. int[] result = new int[nums.length];
  6. int max = nums[0];
  7. result[0] = nums[0];
  8. for(int i = 1; i < nums.length; i++) {
  9. // f(i + 1) = max(f(i) + n[i + 1], n[i + 1])
  10. result[i] = Math.max(nums[i] + result[i - 1], nums[i]);
  11. max = Math.max(max, result[i]);
  12. }
  13. return max;
  14. }
  15. }

54 Spiral Matrix

https://leetcode.com/problems/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].

代码

  1. public class Solution {
  2. public List<Integer> spiralOrder(int[][] matrix) {
  3. List<Integer> result = new ArrayList<Integer>();
  4. if (matrix == null || matrix.length == 0) {
  5. return result;
  6. }
  7. int startx = 0, endx = matrix.length - 1;
  8. int starty = 0, endy = matrix[0].length - 1;
  9. while (startx <= endx && starty <= endy) {
  10. for (int y = starty; y <= endy; y++) {
  11. result.add(matrix[startx][y]);
  12. }
  13. for (int x = startx + 1; x <= endx; x++) {
  14. result.add(matrix[x][endy]);
  15. }
  16. if (startx == endx || starty == endy) {
  17. break;
  18. }
  19. for (int y = endy - 1; y >= starty; y--) {
  20. result.add(matrix[endx][y]);
  21. }
  22. for (int x = endx - 1; x >= startx + 1; x--) {
  23. result.add(matrix[x][starty]);
  24. }
  25. startx++;
  26. starty++;
  27. endx--;
  28. endy--;
  29. }
  30. return result;
  31. }
  32. }

59 Spiral Matrix II

https://leetcode.com/problems/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 ]
]

代码

  1. public class Solution {
  2. public int[][] generateMatrix(int n) {
  3. if (n <= 0) {
  4. return new int[0][0];
  5. }
  6. int[][] matrix = new int[n][n];
  7. int num = 1;
  8. int startx = 0, endx = n - 1;
  9. int starty = 0, endy = n - 1;
  10. while (startx <= endx && starty <= endy) {
  11. for (int y = starty; y <= endy; y++) {
  12. matrix[startx][y] = num++;
  13. }
  14. for (int x = startx + 1; x <= endx; x++) {
  15. matrix[x][endy] = num++;
  16. }
  17. if (startx == endx || starty == endy) {
  18. break;
  19. }
  20. for (int y = endy - 1; y >= starty; y--) {
  21. matrix[endx][y] = num++;
  22. }
  23. for (int x = endx - 1; x >= startx + 1; x--) {
  24. matrix[x][starty] = num++;
  25. }
  26. startx++;
  27. starty++;
  28. endx--;
  29. endy--;
  30. }
  31. return matrix;
  32. }
  33. }

56 Merge Intervals

https://leetcode.com/problems/merge-intervals/

题目描述

Given a collection of intervals, merge all overlapping intervals.

For example,

Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

代码

  1. /**
  2. * Definition for an interval.
  3. * public class Interval {
  4. * int start;
  5. * int end;
  6. * Interval() { start = 0; end = 0; }
  7. * Interval(int s, int e) { start = s; end = e; }
  8. * }
  9. */
  10. class Solution {
  11. public List<Interval> merge(List<Interval> intervals) {
  12. List<Interval> ans = new ArrayList<>();
  13. if (intervals == null || intervals.size() == 0) {
  14. return ans;
  15. }
  16. // sort by start
  17. Collections.sort(intervals, new Comparator<Interval>() {
  18. @Override
  19. public int compare(Interval o1, Interval o2) {
  20. return o1.start != o2.start ? o1.start - o2.start : o1.end - o2.end;
  21. }
  22. });
  23. Interval o1 = intervals.get(0);
  24. for(int i = 1; i < intervals.size(); i++) {
  25. Interval o2 = intervals.get(i);
  26. if (o1.end >= o2.start) {
  27. o1 = new Interval(o1.start, Math.max(o1.end, o2.end));
  28. } else {
  29. ans.add(o1);
  30. o1 = o2;
  31. }
  32. }
  33. ans.add(o1);
  34. return ans;
  35. }
  36. }

57 Insert Interval

https://leetcode.com/problems/insert-interval/

题目描述

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

代码

  1. /**
  2. * Definition for an interval.
  3. * public class Interval {
  4. * int start;
  5. * int end;
  6. * Interval() { start = 0; end = 0; }
  7. * Interval(int s, int e) { start = s; end = e; }
  8. * }
  9. */
  10. class Solution {
  11. public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
  12. List<Interval> result = new ArrayList<>();
  13. int i = 0;
  14. // add all the intervals ending before newInterval starts
  15. while (i < intervals.size() && intervals.get(i).end < newInterval.start)
  16. result.add(intervals.get(i++));
  17. // merge all overlapping intervals to one considering newInterval
  18. while (i < intervals.size() && intervals.get(i).start <= newInterval.end) {
  19. newInterval = new Interval( // we could mutate newInterval here also
  20. Math.min(newInterval.start, intervals.get(i).start),
  21. Math.max(newInterval.end, intervals.get(i).end));
  22. i++;
  23. }
  24. result.add(newInterval); // add the union of intervals we got
  25. // add all the rest
  26. while (i < intervals.size())
  27. result.add(intervals.get(i++));
  28. return result;
  29. }
  30. }

62 Unique Paths

https://leetcode.com/problems/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.

代码

  1. class Solution {
  2. public int uniquePaths(int m, int n) {
  3. // 可以优化成一维数组
  4. int[][] dp = new int[m][n];
  5. for(int i = 0; i < m; i++) {
  6. for(int j = 0; j < n; j++) {
  7. if(i == 0 || j == 0) {
  8. dp[i][j] = 1;
  9. } else {
  10. dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
  11. }
  12. }
  13. }
  14. return dp[m - 1][n - 1];
  15. }
  16. }

63 Unique Paths II

https://leetcode.com/problems/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.

代码

  1. class Solution {
  2. public int uniquePathsWithObstacles(int[][] grid) {
  3. if(grid == null || grid.length == 0 ) return 0;
  4. int m = grid.length, n = grid[0].length;
  5. int[][] dp = new int[m][n];
  6. // 初始化行
  7. for(int i = 0; i < n; i++) {
  8. if(grid[0][i] == 1) break;
  9. dp[0][i] = 1;
  10. }
  11. // 初始化列
  12. for(int i = 0; i < m; i++) {
  13. if(grid[i][0] == 1) break;
  14. dp[i][0] = 1;
  15. }
  16. for(int i = 1; i < m; i++) {
  17. for(int j = 1; j < n; j++) {
  18. if(grid[i][j] == 1) {
  19. dp[i][j] = 0;
  20. } else {
  21. dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
  22. }
  23. }
  24. }
  25. return dp[m - 1][n - 1];
  26. }
  27. }

64 Minimum Path Sum

https://leetcode.com/problems/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.

Example 1:

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

Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.

代码

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

66 Plus One

https://leetcode.com/problems/plus-one/

题目描述

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

You may assume the integer do not contain any leading zero, except the number 0 itself.

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

代码

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

73 Set Matrix Zeroes

https://leetcode.com/problems/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(mn) 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?

代码

  1. public class Solution {
  2. public void setZeroes(int[][] matrix) {
  3. if (matrix == null || matrix.length == 0) {
  4. return;
  5. }
  6. int mx = matrix.length;
  7. int my = matrix[0].length;
  8. boolean xflag = false, yflag = false;
  9. for (int i = 0; i < mx; i++) {
  10. if (matrix[i][0] == 0) {
  11. xflag = true;
  12. break;
  13. }
  14. }
  15. for (int i = 0; i < my; i++) {
  16. if (matrix[0][i] == 0) {
  17. yflag = true;
  18. break;
  19. }
  20. }
  21. for (int i = 1; i < mx; i++) {
  22. for (int j = 1; j < my; j++) {
  23. if (matrix[i][j] == 0) {
  24. matrix[i][0] = 0;
  25. matrix[0][j] = 0;
  26. }
  27. }
  28. }
  29. for (int i = 1; i < mx; i++) {
  30. if (matrix[i][0] == 0) {
  31. for (int j = 0; j < my; j++) {
  32. matrix[i][j] = 0;
  33. }
  34. }
  35. }
  36. for (int i = 0; i < my; i++) {
  37. if (matrix[0][i] == 0) {
  38. for (int j = 0; j < mx; j++) {
  39. matrix[j][i] = 0;
  40. }
  41. }
  42. }
  43. if (xflag) {
  44. for (int i = 0; i < mx; i++) {
  45. matrix[i][0] = 0;
  46. }
  47. }
  48. if (yflag) {
  49. for (int i = 0; i < my; i++) {
  50. matrix[0][i] = 0;
  51. }
  52. }
  53. }
  54. }

75 Sort Colors

https://leetcode.com/problems/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?

代码

  1. class Solution {
  2. public void sortColors(int[] nums) {
  3. int start = 0, end = nums.length - 1;
  4. for(int i = 0; i <= end; i++) {
  5. // 顺序不能换,因为i后面可能换到0,但是i前面是不可能有2的
  6. while(nums[i] == 2 && i < end) swap(nums, i, end--);
  7. while(nums[i] == 0 && i > start) swap(nums, i, start++);
  8. }
  9. }
  10. private void swap(int[] nums, int i, int j) {
  11. int tmp = nums[i];
  12. nums[i] = nums[j];
  13. nums[j] = tmp;
  14. }
  15. }

78 Subsets

https://leetcode.com/problems/subsets/

题目描述

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

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

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

代码

  1. class Solution {
  2. public List<List<Integer>> subsets(int[] nums) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. if(nums == null) return ans;
  5. robot(0, nums, ans, new ArrayList<Integer>());
  6. return ans;
  7. }
  8. private void robot(int start, int[] nums, List<List<Integer>> ans, List<Integer> tmp) {
  9. ans.add(new ArrayList(tmp));
  10. for(int i = start; i < nums.length; i++) {
  11. tmp.add(nums[i]);
  12. robot(i + 1, nums, ans, tmp);
  13. tmp.remove(tmp.size() - 1);
  14. }
  15. }
  16. }

90 Subsets II

https://leetcode.com/problems/subsets-ii/

题目描述

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

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

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

代码

  1. class Solution {
  2. public List<List<Integer>> subsetsWithDup(int[] nums) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. Set<List<Integer>> ansSet = new HashSet<>();
  5. Arrays.sort(nums); // 先排序
  6. robot(0, nums, ansSet, new ArrayList<Integer>());
  7. ans.addAll(ansSet);
  8. return ans;
  9. }
  10. private void robot(int start, int[] nums, Set<List<Integer>> ans, List<Integer> tmp) {
  11. ans.add(new ArrayList(tmp));
  12. for(int i = start; i < nums.length; i++) {
  13. tmp.add(nums[i]);
  14. robot(i + 1, nums, ans, tmp);
  15. tmp.remove(tmp.size() - 1);
  16. }
  17. }
  18. }

79 Word Search

https://leetcode.com/problems/word-search/

题目描述

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

代码

  1. public class Solution {
  2. public static boolean exist(char[][] board, String word) {
  3. if (board == null || board[0].length == 0 || board.length == 0
  4. || word == null) {
  5. return false;
  6. }
  7. int rows = board.length;
  8. int cols = board[0].length;
  9. boolean[] visited = new boolean[rows * cols];
  10. int pathLength = 0;
  11. for (int row = 0; row < rows; row++) {
  12. for (int col = 0; col < cols; col++) {
  13. if (dfs(board, rows, cols, row, col, word, pathLength, visited)) {
  14. return true;
  15. }
  16. }
  17. }
  18. return false;
  19. }
  20. public static boolean dfs(char[][] board, int rows, int cols, int row,
  21. int col, String word, int pathLength, boolean[] visited) {
  22. if (pathLength == word.length()) {
  23. return true;
  24. }
  25. boolean hasPath = false;
  26. if (row >= 0 && row < rows && col >= 0 && col < cols
  27. && board[row][col] == word.charAt(pathLength)
  28. && !visited[row * cols + col]) {
  29. pathLength++;
  30. visited[row * cols + col] = true;
  31. hasPath = dfs(board, rows, cols, row, col - 1, word, pathLength,
  32. visited)
  33. || dfs(board, rows, cols, row - 1, col, word, pathLength,
  34. visited)
  35. || dfs(board, rows, cols, row, col + 1, word, pathLength,
  36. visited)
  37. || dfs(board, rows, cols, row + 1, col, word, pathLength,
  38. visited);
  39. if (!hasPath) {
  40. pathLength--;
  41. visited[row * cols + col] = false;
  42. }
  43. }
  44. return hasPath;
  45. }
  46. }

84 Largest Rectangle in Histogram

https://leetcode.com/problems/largest-rectangle-in-histogram/

题目描述

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,

Given heights = [2,1,5,6,2,3],
return 10.

代码

  1. class Solution {
  2. public int largestRectangleArea(int[] A) {
  3. int area = 0;
  4. for (int i = 0; i < A.length; i++) {
  5. // 每找到局部峰值,向前遍历数组
  6. if(i + 1 < A.length && A[i + 1] >= A[i]) continue;
  7. int min = A[i];
  8. for (int j = i; j >= 0; j--) {
  9. min = Math.min(min, A[j]);
  10. area = Math.max(area, (i + 1 - j) * min);
  11. }
  12. }
  13. return area;
  14. }
  15. }

85 Maximal Rectangle

https://leetcode.com/problems/maximal-rectangle/

题目描述

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 6.

代码

  1. class Solution {
  2. public int maximalRectangle(char[][] matrix) {
  3. if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
  4. int m = matrix.length, n = matrix[0].length;
  5. int[][] height = new int[m][n];
  6. // height[i][j] 表示第i行j列的1的高度
  7. for(int i = 0; i < m; i++) {
  8. for(int j = 0; j < n; j++) {
  9. if(matrix[i][j] == '1') {
  10. height[i][j] = (i >= 1 ? height[i - 1][j] : 0) + 1;
  11. }
  12. }
  13. }
  14. int area = 0;
  15. for(int i = 0; i < m; i++) {
  16. area = Math.max(area, largestRectangleArea(height[i]));
  17. }
  18. return area;
  19. }
  20. public int largestRectangleArea(int[] A) {
  21. int area = 0;
  22. for (int i = 0; i < A.length; i++) {
  23. // 每找到局部峰值,向前遍历数组
  24. if(i + 1 < A.length && A[i + 1] >= A[i]) continue;
  25. int min = A[i];
  26. for (int j = i; j >= 0; j--) {
  27. min = Math.min(min, A[j]);
  28. area = Math.max(area, (i + 1 - j) * min);
  29. }
  30. }
  31. return area;
  32. }
  33. }

88 Merge Sorted Array

https://leetcode.com/problems/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.

代码

  1. class Solution {
  2. public void merge(int[] A, int m, int[] B, int n) {
  3. int i = m - 1, j = n - 1, end = m + n - 1;
  4. while(i >= 0 && j >= 0) {
  5. if(A[i] > B[j]) A[end--] = A[i--];
  6. else A[end--] = B[j--];
  7. }
  8. while(j >= 0) A[end--] = B[j--];
  9. }
  10. }

118 Pascal's Triangle

https://leetcode.com/problems/pascals-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]
]

代码

  1. class Solution {
  2. public List<List<Integer>> generate(int numRows) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. if(numRows <= 0) return ans;
  5. int count = 0;
  6. while(count < numRows) {
  7. List<Integer> last = count > 0 ? ans.get(count - 1) : new ArrayList<>();
  8. List<Integer> tmp = new ArrayList();
  9. for(int i = 0; i <= count; i++) {
  10. if(i == 0 || i == count) tmp.add(1);
  11. else tmp.add(last.get(i - 1) + last.get(i));
  12. }
  13. ans.add(tmp);
  14. count++;
  15. }
  16. return ans;
  17. }
  18. }

119 Pascal's Triangle II

https://leetcode.com/problems/pascals-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?

代码

  1. class Solution {
  2. public List<Integer> getRow(int rowIndex) {
  3. List<Integer> tmp = new ArrayList<>();
  4. if(rowIndex < 0) return tmp;
  5. List<Integer> pre = new ArrayList<>();
  6. int k = 0;
  7. while(k <= rowIndex) {
  8. for(int i = 0; i <= k; i++) {
  9. if(i == 0 || i == k) tmp.add(1);
  10. else tmp.add(pre.get(i - 1) + pre.get(i));
  11. }
  12. pre = new ArrayList(tmp);
  13. tmp.clear();
  14. k++;
  15. }
  16. return pre;
  17. }
  18. }

120 Triangle

https://leetcode.com/problems/triangle/

题目描述

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

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

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

代码

  1. class Solution {
  2. public int minimumTotal(List<List<Integer>> triangle) {
  3. int k = triangle.size();
  4. if(k == 0) return 0;
  5. List<Integer> pre = triangle.get(0);
  6. List<Integer> ans = new ArrayList<>();
  7. for(int i = 1; i < triangle.size(); i++) {
  8. List<Integer> now = triangle.get(i);
  9. for(int j = 0; j < now.size(); j++) {
  10. if(j == 0) ans.add(now.get(j) + pre.get(0));
  11. else if(j == now.size() - 1) ans.add(now.get(j) + pre.get(j - 1));
  12. else ans.add(now.get(j) + Math.min(pre.get(j), pre.get(j - 1)));
  13. }
  14. pre = new ArrayList(ans);
  15. ans.clear();
  16. }
  17. return Collections.min(pre);
  18. }
  19. }

121 Best Time to Buy and Sell Stock

https://leetcode.com/problems/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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

代码

  1. class Solution {
  2. public int maxProfit(int[] prices) {
  3. int maxProfit = 0;
  4. // 存储从prices[0..i]的最小值
  5. int lowest = Integer.MAX_VALUE;
  6. for (int v : prices) {
  7. lowest = Math.min(v, lowest);
  8. maxProfit = Math.max(maxProfit, v - lowest);
  9. }
  10. return maxProfit;
  11. }
  12. }

122 Best Time to Buy and Sell Stock II

https://leetcode.com/problems/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).

代码

  1. class Solution {
  2. public int maxProfit(int[] prices) {
  3. // 只要有利润就卖,就是最优解。
  4. int profit = 0;
  5. for(int i = 1; i < prices.length; i++) {
  6. if(prices[i] > prices[i - 1]) {
  7. profit += prices[i] - prices[i - 1];
  8. }
  9. }
  10. return profit;
  11. }
  12. }

123 Best Time to Buy and Sell Stock III

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

题目描述

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 at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

代码

  1. class Solution {
  2. public int maxProfit(int[] prices) {
  3. if (prices == null || prices.length == 0) {
  4. return 0;
  5. }
  6. int n = prices.length;
  7. /**
  8. * l[i][j]: 第i天可进行j次交易,且最后一次交易在最后一天卖出
  9. * g[i][j]: 第i天最多j次交易的最大利润
  10. *
  11. * l[i][j] = max(l[i-1][j], g[i-1][j-1]) + diff
  12. * g[i][j] = max(l[i][j], g[i-1][j])
  13. *
  14. * l[i][j](最后一次交易在最后一天卖出)公式分2种情况:
  15. * 1. l[i-1][j] + diff:最后一次交易在i-1天卖出,加上diff相当于i-1天没卖,最后一天卖,不增加交易次数
  16. * 2. g[i-1][j-1] + diff: i-1天卖出,结果不会比1好;i-1天未卖出,则可以卖,增加交易次数
  17. *
  18. * 可以转化为一维数组 int[3]
  19. */
  20. int[][] l = new int[n][3];
  21. int[][] g = new int[n][3];
  22. for (int i = 1; i < n; i++) {
  23. int diff = prices[i] - prices[i - 1];
  24. for (int j = 1; j <= 2; j++) {
  25. l[i][j] = Math.max(l[i - 1][j], g[i - 1][j - 1]) + diff;
  26. g[i][j] = Math.max(l[i][j], g[i - 1][j]);
  27. }
  28. }
  29. return g[n - 1][4];
  30. }
  31. }

188 Best Time to Buy and Sell Stock IV

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/

题目描述

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 at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

代码

  1. class Solution {
  2. public int maxProfit(int k, int[] prices) {
  3. if (prices == null || prices.length == 0) {
  4. return 0;
  5. }
  6. if(k >= prices.length) return maxProfit(prices);
  7. int n = prices.length;
  8. int[] l = new int[k + 1];
  9. int[] g = new int[k + 1];
  10. for (int i = 1; i < n; i++) {
  11. int diff = prices[i] - prices[i - 1];
  12. for (int j = k; j >= 1; j--) {
  13. l[j] = Math.max(l[j], g[j - 1]) + diff;
  14. g[j] = Math.max(l[j], g[j]);
  15. }
  16. }
  17. return g[k];
  18. }
  19. public int maxProfit(int[] prices) {
  20. // 只要有利润就卖,就是最优解。
  21. int profit = 0;
  22. for(int i = 1; i < prices.length; i++) {
  23. if(prices[i] > prices[i - 1]) {
  24. profit += prices[i] - prices[i - 1];
  25. }
  26. }
  27. return profit;
  28. }
  29. }

309 Best Time to Buy and Sell Stock with Cooldown

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/

题目描述

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) with the following restrictions:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:

prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]

代码

  1. class Solution {
  2. public int maxProfit(int[] prices) {
  3. if(prices == null || prices.length == 0) return 0;
  4. int n = prices.length;
  5. // buy[i] 表示第i天持有股票,最大利润
  6. int[] buy = new int[n];
  7. // sell[i] 表示第i天为持股,最大利润
  8. int[] sell = new int[n];
  9. buy[0] = -prices[0];
  10. sell[0] = 0;
  11. for(int i = 1; i < n; i++) {
  12. buy[i] = Math.max(buy[i - 1], (i > 1 ? sell[i - 2] : 0) - prices[i]);
  13. sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]);
  14. }
  15. return sell[n - 1];
  16. }
  17. }

714 Best Time to Buy and Sell Stock with Transaction Fee

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/

题目描述

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

Example 1:

Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Note:

0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.

代码

  1. class Solution {
  2. public int maxProfit(int[] prices, int fee) {
  3. if(prices == null || prices.length == 0) return 0;
  4. int n = prices.length;
  5. // buy[i] 表示第i天持有股票,最大利润
  6. int[] buy = new int[n];
  7. // sell[i] 表示第i天为持股,最大利润
  8. int[] sell = new int[n];
  9. buy[0] = -prices[0];
  10. sell[0] = 0;
  11. for(int i = 1; i < n; i++) {
  12. buy[i] = Math.max(buy[i - 1], sell[i - 1] - prices[i]);
  13. sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i] - fee);
  14. }
  15. return sell[n - 1];
  16. }
  17. }

128 Longest Consecutive Sequence

https://leetcode.com/problems/longest-consecutive-sequence/

题目描述

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

代码

  1. class Solution {
  2. public int longestConsecutive(int[] nums) {
  3. if(nums == null || nums.length == 0) return 0;
  4. Map<Integer, Integer> map = new HashMap<>();
  5. int ans = 0;
  6. for(int i = 0; i < nums.length; i++) {
  7. if(!map.containsKey(nums[i])) {
  8. int left = map.containsKey(nums[i] - 1) ? map.get(nums[i] - 1) : 0;
  9. int right = map.containsKey(nums[i] + 1) ? map.get(nums[i] + 1) : 0;
  10. int times = left + right + 1;
  11. map.put(nums[i], times);
  12. ans = Math.max(ans, times);
  13. map.put(nums[i] - left, times);
  14. map.put(nums[i] + right, times);
  15. }
  16. }
  17. return ans;
  18. }
  19. }

152 Maximum Product Subarray

https://leetcode.com/problems/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.

代码

  1. class Solution {
  2. public int maxProduct(int[] nums) {
  3. int maxLocal = nums[0];
  4. int minLocal = nums[0];
  5. int global = nums[0];
  6. for(int i = 1; i < nums.length; i++) {
  7. int temp = maxLocal;
  8. maxLocal = Math.max(Math.max(nums[i] * temp, nums[i] * minLocal), nums[i]);
  9. minLocal = Math.min(Math.min(nums[i] * temp, nums[i] * minLocal), nums[i]);
  10. global = Math.max(global, maxLocal);
  11. }
  12. return global;
  13. }
  14. }

153 Find Minimum in Rotated Sorted Array

https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/

题目描述

Suppose an array sorted in ascending order 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.

代码

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

162 Find Peak Element

https://leetcode.com/problems/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.

click to show spoilers.

Note:
Your solution should be in logarithmic complexity.

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

代码

  1. class Solution {
  2. public int findPeakElement(int[] nums) {
  3. if(nums == null || nums.length == 0) return 0;
  4. for(int i = 0; i < nums.length; i++) {
  5. boolean left = i == 0 ? true : nums[i] > nums[i - 1];
  6. boolean right = i == nums.length - 1 ? true : nums[i] > nums[i + 1];
  7. if(left && right) return i;
  8. }
  9. return 0;
  10. }
  11. }

169 Majority Element

https://leetcode.com/problems/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.

代码

  1. class Solution {
  2. public int majorityElement(int[] nums) {
  3. if(nums == null || nums.length == 0) return 0;
  4. int count = 0, ans = 0;
  5. for(int v : nums) {
  6. if(count == 0) {
  7. ans = v;
  8. count = 1;
  9. } else if(v != ans) {
  10. count--;
  11. } else {
  12. count++;
  13. }
  14. }
  15. return ans;
  16. }
  17. }

229 Majority Element II

https://leetcode.com/problems/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.

代码

  1. class Solution {
  2. public List<Integer> majorityElement(int[] nums) {
  3. List<Integer> ans = new ArrayList<>();
  4. if(nums == null || nums.length == 0) return ans;
  5. int n1 = 0, n2 = 0, c1 = 0, c2 = 0;
  6. for(int v : nums) {
  7. if(v == n1) c1++;
  8. else if(v == n2) c2++;
  9. else if(c1 == 0) {
  10. c1 = 1;
  11. n1 = v;
  12. }
  13. else if(c2 == 0) {
  14. c2 = 1;
  15. n2 = v;
  16. }
  17. else {
  18. c1--;
  19. c2--;
  20. }
  21. }
  22. c1 = 0; c2 = 0;
  23. for(int v : nums) {
  24. if(v == n1) c1++;
  25. else if(v == n2) c2++;
  26. }
  27. if(c1 > nums.length / 3) ans.add(n1);
  28. if(c2 > nums.length / 3) ans.add(n2);
  29. return ans;
  30. }
  31. }

189 Rotate Array

https://leetcode.com/problems/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.

代码

  1. public class Solution { static 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 static 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. }}

209 Minimum Size Subarray Sum

https://leetcode.com/problems/minimum-size-subarray-sum/

题目描述

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous 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.

click to show more practice.

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.

代码

  1. class Solution {
  2. public int minSubArrayLen(int s, int[] nums) {
  3. if(nums == null || nums.length == 0) return 0;
  4. int start = 0, end = 0, sum = 0, ans = Integer.MAX_VALUE;
  5. while(end < nums.length && start < nums.length) {
  6. // 滑动窗口,end
  7. while(end < nums.length && sum < s) {
  8. sum += nums[end++];
  9. if(sum >= s) {
  10. ans = Math.min(ans, end - start);
  11. }
  12. }
  13. // 滑动窗口,start
  14. while(start < nums.length && sum >= s) {
  15. sum -= nums[start++];
  16. if(sum < s) {
  17. ans = Math.min(ans, end - start + 1);
  18. }
  19. }
  20. }
  21. return ans == Integer.MAX_VALUE ? 0 : ans;
  22. }
  23. }

217 Contains Duplicate

https://leetcode.com/problems/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.

代码

  1. class Solution {
  2. public boolean containsDuplicate(int[] nums) {
  3. if(nums == null || nums.length == 0) return false;
  4. Set<Integer> set = new HashSet<>();
  5. for(int v : nums) {
  6. if(set.contains(v)) return true;
  7. set.add(v);
  8. }
  9. return false;
  10. }
  11. }

219 Contains Duplicate II

https://leetcode.com/problems/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 absolute difference between i and j is at most k.

代码

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

238 Product of Array Except Self

https://leetcode.com/problems/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.)

代码

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

268 Missing Number

https://leetcode.com/problems/missing-number/

题目描述

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

Example 1

Input: [3,0,1]
Output: 2

Example 2

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

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.

代码

  1. class Solution {
  2. public int missingNumber(int[] nums) {
  3. if(nums == null) return 0;
  4. int sum = (1 + nums.length) * nums.length / 2;
  5. for(int v : nums) {
  6. sum -= v;
  7. }
  8. return sum;
  9. }
  10. }

283 Move Zeroes

https://leetcode.com/problems/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:

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

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

代码

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

287 Find the Duplicate Number

https://leetcode.com/problems/find-the-duplicate-number/

题目描述

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:

You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.

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

代码

  1. public class Solution {
  2. // https://segmentfault.com/a/1190000003817671
  3. public int findDuplicate(int[] nums) {
  4. int slow = 0;
  5. int fast = 0;
  6. // 找到快慢指针相遇的地方
  7. do{
  8. slow = nums[slow];
  9. fast = nums[nums[fast]];
  10. } while(slow != fast);
  11. int find = 0;
  12. // 用一个新指针从头开始,直到和慢指针相遇
  13. while(find != slow){
  14. slow = nums[slow];
  15. find = nums[find];
  16. }
  17. return find;
  18. }
  19. }

442 Find All Duplicates in an Array

https://leetcode.com/problems/find-all-duplicates-in-an-array/

题目描述

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

代码

  1. class Solution {
  2. public List<Integer> findDuplicates(int[] nums) {
  3. List<Integer> ans = new ArrayList<>();
  4. for(int i = 0; i < nums.length; i++) {
  5. if(nums[i] != nums[nums[i] - 1]) {
  6. swap(nums, i, nums[i] - 1);
  7. i--;
  8. }
  9. }
  10. System.out.println(Arrays.toString(nums));
  11. for(int i = 0; i < nums.length; i++) {
  12. if(nums[i] != i + 1) {
  13. ans.add(nums[i]);
  14. }
  15. }
  16. return ans;
  17. }
  18. private void swap(int[] nums, int i, int j) {
  19. int tmp = nums[i];
  20. nums[i] = nums[j];
  21. nums[j] = tmp;
  22. }
  23. }

289 Game of Life

https://leetcode.com/problems/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):

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

Follow up:

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.
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.

代码

  1. class Solution {
  2. public void gameOfLife(int[][] board) {
  3. final int m = board.length;
  4. final int n = board[0].length;
  5. /**
  6. 状态0:死细胞转为死细胞
  7. 状态1:活细胞转为活细胞
  8. 状态2:活细胞转为死细胞
  9. 状态3:死细胞转为活细胞
  10. **/
  11. // encode
  12. for (int i = 0; i < m; ++i) {
  13. for (int j = 0; j < n; ++j) {
  14. int live = countLive(board, i, j); // number of live cells
  15. if (board[i][j] == 0 && live == 3) {
  16. board[i][j] = 3;
  17. } else if (board[i][j] == 1 && (live < 2 || live > 3)) {
  18. board[i][j] = 2;
  19. }
  20. }
  21. }
  22. // decode
  23. for (int i = 0; i < m; ++i) {
  24. for (int j = 0; j < n; ++j) {
  25. board[i][j] %= 2;
  26. }
  27. }
  28. }
  29. private int countLive(int[][] nums, int i, int j) {
  30. int count = 0;
  31. int m = nums.length, n = nums[0].length;
  32. for(int x = i - 1; x <= i + 1; x++) {
  33. for(int y = j - 1; y <= j + 1; y++) {
  34. if(x == i && y == j) continue;
  35. if(x >= 0 && x < m && y >= 0 && y < n && (nums[x][y] == 1 || nums[x][y] == 2)) {
  36. count++;
  37. }
  38. }
  39. }
  40. return count;
  41. }
  42. }

380 Insert Delete GetRandom O(1)

https://leetcode.com/problems/insert-delete-getrandom-o1/

题目描述

Design a data structure that supports all following operations in average O(1) time.

Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

代码

  1. class RandomizedSet {
  2. private List<Integer> list;
  3. private Map<Integer, Integer> map;
  4. private Random random;
  5. /** Initialize your data structure here. */
  6. public RandomizedSet() {
  7. list = new ArrayList<>();
  8. map = new HashMap<>();
  9. random = new Random();
  10. }
  11. /**
  12. * Inserts a value to the set. Returns true if the set did not already contain
  13. * the specified element.
  14. */
  15. public boolean insert(int val) {
  16. if (map.containsKey(val)) {
  17. return false;
  18. }
  19. list.add(val);
  20. map.put(val, list.size() - 1);
  21. return true;
  22. }
  23. /**
  24. * Removes a value from the set. Returns true if the set contained the specified
  25. * element.
  26. */
  27. public boolean remove(int val) {
  28. if (!map.containsKey(val)) {
  29. return false;
  30. }
  31. int index = map.get(val);
  32. list.set(index, list.get(list.size() - 1));
  33. map.put(list.get(index), index);
  34. map.remove(val);
  35. list.remove(list.size() - 1);
  36. return true;
  37. }
  38. /** Get a random element from the set. */
  39. public int getRandom() {
  40. if (list.size() == 0) {
  41. return 0;
  42. }
  43. return list.get(random.nextInt(list.size()));
  44. }
  45. }

381 Insert Delete GetRandom O(1) - Duplicates allowed

https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/

题目描述

Design a data structure that supports all following operations in average O(1) time.
Note: Duplicate elements are allowed.

Example:

// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);

// getRandom should return 1 and 2 both equally likely.
collection.getRandom();

代码

  1. class RandomizedCollection {
  2. private List<Integer> list;
  3. private Map<Integer, Set<Integer>> map;
  4. private Random random;
  5. /** Initialize your data structure here. */
  6. public RandomizedCollection() {
  7. list = new ArrayList<>();
  8. map = new HashMap<>();
  9. random = new Random();
  10. }
  11. /**
  12. * Inserts a value to the set. Returns true if the set did not already contain
  13. * the specified element.
  14. */
  15. public boolean insert(int val) {
  16. boolean flag = false;
  17. if (!map.containsKey(val)) {
  18. flag = true;
  19. map.put(val, new HashSet<Integer>());
  20. }
  21. map.get(val).add(list.size());
  22. list.add(val);
  23. return flag;
  24. }
  25. /**
  26. * Removes a value from the set. Returns true if the set contained the specified
  27. * element.
  28. */
  29. public boolean remove(int val) {
  30. if (!map.containsKey(val)) {
  31. return false;
  32. }
  33. int removed = map.get(val).iterator().next();
  34. map.get(val).remove(removed);
  35. if (removed < list.size() - 1) {
  36. Integer tail = list.get(list.size() - 1);
  37. list.set(removed, tail);
  38. map.get(tail).remove(list.size() - 1);
  39. map.get(tail).add(removed);
  40. }
  41. list.remove(list.size() - 1);
  42. if (map.get(val).size() == 0) {
  43. map.remove(val);
  44. }
  45. return true;
  46. }
  47. /** Get a random element from the set. */
  48. public int getRandom() {
  49. if (list.size() == 0) {
  50. return 0;
  51. }
  52. return list.get(random.nextInt(list.size()));
  53. }
  54. }
  55. /**
  56. * Your RandomizedCollection object will be instantiated and called as such:
  57. * RandomizedCollection obj = new RandomizedCollection();
  58. * boolean param_1 = obj.insert(val);
  59. * boolean param_2 = obj.remove(val);
  60. * int param_3 = obj.getRandom();
  61. */

414 Third Maximum Number

https://leetcode.com/problems/third-maximum-number/

题目描述

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

代码

  1. class Solution {
  2. public int thirdMax(int[] nums) {
  3. long max0 = Long.MIN_VALUE;
  4. long max1 = Long.MIN_VALUE;
  5. long max2 = Long.MIN_VALUE;
  6. for(int v : nums) {
  7. if(max0 < v) {
  8. max2 = max1;
  9. max1 = max0;
  10. max0 = (long)v;
  11. } else if(max1 < v && v < max0) {
  12. max2 = max1;
  13. max1 = (long)v;
  14. } else if(max2 < v && v < max1){
  15. max2 = (long)v;
  16. }
  17. }
  18. return (int) (max2 == Long.MIN_VALUE ? max0 : max2);
  19. }
  20. }

485 Max Consecutive Ones

https://leetcode.com/problems/max-consecutive-ones/

题目描述

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

Input: [1,1,0,1,1,1]
Output: 3

Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.

Note:

The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000

代码

  1. class Solution {
  2. public int findMaxConsecutiveOnes(int[] nums) {
  3. int ans = 0;
  4. for(int i = 0; i < nums.length; i++) {
  5. if(nums[i] == 1) {
  6. int count = 0;
  7. while(i < nums.length && nums[i] == 1) {
  8. count++;
  9. i++;
  10. }
  11. ans = Math.max(ans, count);
  12. }
  13. }
  14. return ans;
  15. }
  16. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注