977.有序数组的平方
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
双指针:时间复杂度O(n)
class Solution {
public int[] sortedSquares(int[] nums) {
int[] res = new int[nums.length];
int i = 0;
int j = nums.length-1;
int k = nums.length-1;
while(i <= j){
if(nums[i]*nums[i] > nums[j]*nums[j]){
res[k] = nums[i]*nums[i];
i++;
}
else{
res[k] = nums[j]*nums[j];
j--;
}
k--;
}
return res;
}
}
自己一开始没有思路的话只能想到快排,双指针的方法打开了我的视野
209.长度最小的子数组
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
滑动窗口
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int i,j;
int sum = 0;
int res = 0;
for(i = j = 0; j < nums.length; j++){
sum += nums[j];
while(sum >= target){
sum -= nums[i];
res = j-i+1;
i++;
}
}
return res;
}
}
总结:
终止位置先移动,起始位置后移动。判断条件是sum>=target,长度是j-i+1,注意j-i的值,最后的落脚点时j-i是比长度小2的(跳出循环时i已经导致sum<target,且长度本身就要比j-i大1)最后还要考虑不满足条件的情况,引入result变量来解决,不能直接返回j-i+2
59.螺旋矩阵II
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public int[][] generateMatrix(int n) {
int[][] nums = new int[n][n];
int startx,starty;
int offest;
int i,j,time;
int count = 1;
startx = starty = 0;
offest = 1;
for(time = 0; time < n/2; time++){
i = startx;
j = starty;
for( ; j < n-offest; j++)
nums[i][j] = count++;
for( ; i < n-offest; i++)
nums[i][j] = count++;
for( ; j > starty; j--)
nums[i][j] = count++;
for ( ; i > startx; i--)
nums[i][j] = count++;
startx++;
starty++;
offest++;
}
if(n%2 == 1){
nums[startx][starty] = count;
}
return nums;
}
}
总结:
1.以圈为对象分析,一共是有n/2圈,不能以数的增长作为分析点。
2.每一条边的处理规则要统一。
3.单数和双数都要考虑一下。
本文介绍了在LeetCode平台上三个与数组操作相关的编程题目:有序数组的平方使用双指针优化,长度最小子数组通过滑动窗口技巧求解,以及螺旋矩阵II的生成方法。作者分享了解题思路和关键代码段,展示了在解决这些技术问题时的策略和技巧。
1685

被折叠的 条评论
为什么被折叠?



