数组
# 最大子数组和
class Solution {
public int maxSubArray(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
for( int i =1; i< nums.length; i++){
if(dp[i-1]> 0){
dp[i] = dp[i-1] + nums[i];
}else{
dp[i] = nums[i];
}
}
int max = dp[0];
for(int item: dp){
max = Math.max(max, item);
}
return max;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 合并区间
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a,b)-> a[0] -b[0]);
List<int[]> res = new ArrayList<>();
for(int i = 0; i< intervals.length; i++){
if(res.size() == 0 || intervals[i][0] > res.get(res.size()-1)[1]){
res.add(intervals[i]);
} else{
res.get(res.size() - 1)[1] = Math.max(intervals[i][1], res.get(res.size() - 1)[1]);
}
}
return res.toArray(new int[res.size()][2]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 轮转数组
class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
int[] newArr = new int[n];
for (int i = 0; i < n; i++) {
newArr[(i + k) % n] = nums[i];
}
for(int i = 0; i< newArr.length; i++ ){
nums[i] = newArr[i];
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 除自身以外 数组的乘积
class Solution {
public int[] productExceptSelf(int[] nums) {
if(nums == null || nums.length == 0){
return null;
}
int n = nums.length;
int[] newArr = new int[n];
newArr[0] = 1;
for(int i = 1; i< n; i++){
newArr[i] = nums[i-1] * newArr[i-1];
}
int right = 1;
for(int i = n-1; i>=0; i--){
newArr[i] = newArr[i] * right;
right = right* nums[i];
}
return newArr;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 缺失的第一个正数
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
int temp = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = temp;
}
}
for (int i = 0; i < n; i++) {
if (nums[i] != i + 1) {
return i + 1;
}
}
return n + 1;
}
}
奇淫巧技:
class Solution {
public int firstMissingPositive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (num > 0) {
set.add(num);
}
}
int count = 1;
while (true) {
if (!set.contains(count)) {
return count;
}
count++;
}
}
}
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
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
上次更新: 2024/03/26, 9:03:00