训练营Day2
# 977.有序数组的平方 (opens new window)
由于数组是有序的,我们只需要对比头和尾两个数字的绝对值,就能知道谁的平方数比较大。最大的放在数组的最后一个。然后指针往中间移动即可
package org.example;
class Solution {
public int[] sortedSquares(int[] nums) {
int leftIndex = 0;
int[] newNums = new int[nums.length];
int rightIndex = nums.length-1;
int newIndex = nums.length-1;
while (leftIndex<=rightIndex){
if (Math.abs(nums[leftIndex])>Math.abs(nums[rightIndex])){
newNums[newIndex] = nums[leftIndex] * nums[leftIndex];
newIndex--;
leftIndex++;
}else{
newNums[newIndex] = nums[rightIndex]*nums[rightIndex];
newIndex--;
rightIndex--;
}
}
return newNums;
}
}
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
# 209.长度最小的子数组 (opens new window)
滑动窗口的解题思路:
快指针向右移动的同时,累计总和,当总和sum>target的时候,判断快指针和慢指针之间的长度是不是最短的,如果是存储起来
然后慢指针向右移动,直到sum<target
sum<target的时候,继续移动快指针。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int ans = Integer.MAX_VALUE; //定义答案
int sum = 0; //窗口大小
int leftIndex=0;
int rightIndex=0;
while (rightIndex<nums.length){
sum+=nums[rightIndex];
while (sum>=target){
ans = Math.min(ans,rightIndex-leftIndex+1);
sum-=nums[leftIndex];
leftIndex++;
}
rightIndex++;
}
return ans==Integer.MAX_VALUE?0:ans;
}
}
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
# 59.螺旋矩阵 Ⅱ (opens new window)
纯模拟操作,主要是边界要分清楚。
leetcode里面有很优秀的题解
class Solution {
public int[][] generateMatrix(int n) {
if (n==1){
return new int[][]{{1}};
}
int[][] matrix = new int[n][n]; //新建矩阵
int t=0,r=n-1,b=n-1,l=0; //建立边界
int count = 1;
while (count<=n*n){
//1.从左到右
for (int i=l;i<=r;i++){
matrix[t][i] = count++;
}
t++;
//2.从上到下
for (int i=t;i<=b;i++){
matrix[i][r]=count++;
}
r--;
//3.从右到左
for (int i=r;i>=l;i--){
matrix[b][i]=count++;
}
b--;
//4.从下到上
for (int i=b;i>=t;i--){
matrix[i][l] = count++;
}
l++;
}
return matrix;
}
}
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
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
上次更新: 2023/06/08, 15:18:26