双指针
待第二轮补充。。。
# 移动0
class Solution {
public void moveZeroes(int[] nums) {
if(nums == null || nums.length == 0){
return;
}
int slow = 0;
int fast = 0;
while(fast < nums.length){
if(nums[fast] != 0){
int item = nums[fast];
nums[fast] = nums[slow];
nums[slow] = item;
slow++;
}
fast++;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 盛水最多的容器
class Solution {
public int maxArea(int[] height) {
if(height == null || height.length <= 1){
return 0;
}
int left = 0;
int right = height.length-1;
int res = 0;
while(left < right){
if(height[left] > height[right]){
res = Math.max(res, height[right]* (right-left));
right--;
} else{
res = Math.max(res, height[left]* (right-left));
left++;
}
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 三数之和
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums.length < 3){
return res;
}
Arrays.sort(nums);
for(int i = 0; i< nums.length; i++){
if(nums[i] > 0){
return res;
}
if(i> 0 && nums[i] == nums[i-1]){
continue;
}
int l = i+1;
int r = nums.length-1;
while(l< r){
int sum = nums[l] + nums[i] + nums[r];
if(sum > 0){
r--;
} else if(sum < 0){
l++;
} else {
res.add(Arrays.asList(nums[l] , nums[i] , nums[r]));
// 去重
while(l<r && nums[l] == nums[l+1]){
l++;
}
while(l<r && nums[r] == nums[r-1]){
r--;
}
l++;
r--;
}
}
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 接雨水
class Solution {
public int trap(int[] height) {
int sum= 0;
for (int i = 1; i < height.length-1; i++) {
int max_l = 0;
for (int j = i-1; j >= 0 ; j--) {
if (height[j] > max_l) {
max_l = height[j];
}
}
int max_r = 0;
for (int j = i+1; j < height.length ; j++) {
if (height[j] > max_r) {
max_r = height[j];
}
}
int min = Math.min(max_r, max_l);
if (min > height[i]) {
sum+=min-height[i];
}
}
return sum;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
上次更新: 2024/03/26, 9:03:00