Skip to content

Commit 6003d88

Browse files
author
haotf
committed
三数之和
1 parent f73d6c8 commit 6003d88

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

Diff for: 11.盛最多水的容器.java

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
* @lc app=leetcode.cn id=11 lang=java
3+
*
4+
* [11] 盛最多水的容器
5+
*/
6+
7+
// @lc code=start
8+
class Solution {
9+
public int maxArea(int[] height) {
10+
int max = 0;
11+
int left = 0;
12+
int right = height.length - 1;
13+
14+
while (left < right) {
15+
max = Math.max(max, (right - left) * Math.min(height[left], height[right]));
16+
if (height[left] < height[right]) {
17+
left++;
18+
} else {
19+
right--;
20+
}
21+
}
22+
return max;
23+
}
24+
}
25+
// @lc code=end

Diff for: 15.三数之和.java

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.Comparator;
4+
import java.util.List;
5+
6+
/*
7+
* @lc app=leetcode.cn id=15 lang=java
8+
*
9+
* [15] 三数之和
10+
*/
11+
12+
// @lc code=start
13+
class Solution {
14+
public List<List<Integer>> threeSum(int[] nums) {
15+
Arrays.sort(nums);
16+
return nSum(nums, 0, 3, 0);
17+
}
18+
19+
private List<List<Integer>> nSum(int[] nums, int start, int n, int target) {
20+
List<List<Integer>> res = new ArrayList<>();
21+
if (nums.length < n || n < 2)
22+
return res;
23+
24+
if (n == 2) {
25+
int left = start;
26+
int right = nums.length - 1;
27+
while (left < right) {
28+
int sum = nums[left] + nums[right];
29+
int low = nums[left];
30+
int high = nums[right];
31+
if (sum < target) {
32+
while (nums[left] == low && left < right)
33+
left++;
34+
} else if (sum > target) {
35+
while (nums[right] == high && left < right)
36+
right--;
37+
} else {
38+
List<Integer> rList = new ArrayList<>();
39+
rList.add(nums[left]);
40+
rList.add(nums[right]);
41+
res.add(rList);
42+
while (nums[left] == low && left < right)
43+
left++;
44+
while (nums[right] == high && left < right)
45+
right--;
46+
}
47+
}
48+
} else {
49+
for (int i = start; i < nums.length; i++) {
50+
List<List<Integer>> result = nSum(nums, i + 1, n - 1, target - nums[i]);
51+
52+
for (List<Integer> list : result) {
53+
list.add(0, nums[i]);
54+
res.add(list);
55+
}
56+
while (i < nums.length - 1 && nums[i] == nums[i + 1])
57+
i++;
58+
}
59+
}
60+
return res;
61+
}
62+
}
63+
// @lc code=end

0 commit comments

Comments
 (0)