977.有序数组的平方
1.题目描述
2.适用场景
暴力法:时间复杂度O(n + nlog n)
双指针法:时间复杂度O(n)
3.做题思路
暴力法:先平方后直接排序
双指针法:创建新数组,对比两端大小,将大的平方放进新数组右端,返回值为新数组
4.代码实现
双指针法
class Solution {
public int[] sortedSquares(int[] nums) {
int left=0;
int right = nums.length - 1;
int [] range = new int[nums.length];
int index = range.length - 1;
while (left<=right){
if(nums[left]*nums[left] >=nums[right] * nums[right]){
range[index]=nums[left] * nums[left];
index--;
left++;
}
else{
range[index]=nums[right] * nums[right];
index--;
right--;
}
}
return range;
}
}
5.错误总结
创建数组时错误认为,数组中[数字]为数组最后一个值的序号,正确:数组大小。
没有添加left=right的情况。
<=要连在一起写,长时间使用插件,代码格式忘了。
209.长度最小的子数组
1.题目描述
2.适用场景
动态窗口法
- 时间复杂度:O(n)
3.做题思路
使两个指针像一个窗口右指针向前找到大于所给值时,左指针向前移
4.代码实现
动态窗口法
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int sum = 0;
int result = Integer.MAX_VALUE;
int i = 0;
for(int j = 0;j<nums.length;j++){
sum += nums[j];
while(sum>=target){
result = Math.min(result,j-i+1);
sum -=nums[i];
i++;
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
5.错误总结
使用Math函数时小写
写j<=nums.length数组越界
没有设置result为最大值,使所有返回值都为0;
59.螺旋矩阵II
1.题目描述
2. 适用场景
时间复杂度 O(n^2): 模拟遍历二维矩阵的时间
3.做题思路
不断遍历各个位置,奇数中心点直接赋值
4.代码实现
class Solution {
public int[][] generateMatrix(int n) {
int [][]nums=new int [n][n];
int startx = 0;
int starty = 0;
int loop =1;
int off = 1;
int i,j;
int count =1;
while(loop <= n/2){
for(j=starty;j<n-off;j++){
nums[startx][j] = count;
count++;
}
for(i=startx;i<n-off;i++){
nums[i][j]=count;
count++;
}
for(;j>starty;j--){
nums[i][j]=count;
count++;
}
for(;i>startx;i--){
nums[i][j]=count;
count++;
}
startx++;
starty++;
off++;
loop++;
}
if(n%2!=0){
nums[startx][starty]=count;
}
return nums;
}
}
5.错误总结
将初始y赋值为0导致错误