您现在的位置是:首页 >学无止境 >代码随想录算法训练营第二天|977.有序数组的平方、209.长度最小的子数组、59.螺旋矩阵II网站首页学无止境
代码随想录算法训练营第二天|977.有序数组的平方、209.长度最小的子数组、59.螺旋矩阵II
简介代码随想录算法训练营第二天|977.有序数组的平方、209.长度最小的子数组、59.螺旋矩阵II
leetcode 977 有序数组的平方
题目链接
做题过程
最开始的时候,虽然想到了用双指针的方法进行操作,但想到的是将双指针放在中间位置(nums[k] > 0), 然后左右移动。但这样做容易数组越界。 在查看思路后,修改为从两头往中间跑,而不是中间往两头跑。这样做更容易解决问题。
以下为错误的思路
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = 0;
int temp = 0;
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= 0) {
right = i;
left = right -1;
break;
}
}
while (temp < nums.length) {
if (nums[left] * nums[left] >= nums[right] *nums[right]) {
result[temp] = nums[right] * nums[right];
right++;
temp++;
}
else if (nums[left] * nums[left] < nums[right] *nums[right]) {
result[temp] = nums[left] * nums[left];
left--;
temp++;
}
}
return result;
}
}
解决方法
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int temp = nums.length - 1;
int[] result = new int[nums.length];
while (temp >= 0) {
if (nums[left] * nums[left] >= nums[right] *nums[right]) {
result[temp] = nums[left] * nums[left];
left++;
temp--;
}
else if (nums[left] * nums[left] < nums[right] *nums[right]) {
result[temp] = nums[right] * nums[right];
right--;
temp--;
}
}
return result;
}
}
leetcode 209 长度最小的子数组
题目链接
做题过程
这题是用滑动窗口的方式。应为之前做过这道题目。在做题时很快想到了思路,也知道如何去做。但在写代码时,如何收缩窗口一直没想明白。最后参考答案,利用双指针的方法很快做出。
解决方法
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int result = Integer.MAX_VALUE;
int fast = 0;
int slow = 0;
int total = 0;
for (;fast < nums.length; fast++) {
total += nums[fast];
while (total >= target) {
result = Math.min(result, fast - slow + 1);
total -=nums[slow];
slow++;
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
leetcode 704 二分查找
题目链接
做题过程
这道题以前做过。本质就是通过4个for循环从4条边边上填空。然后收缩在填写内边。知道无边可填。需要注意的是,若n为基数。需要填写中心点位置。
解决方法
class Solution {
public int[][] generateMatrix(int n) {
int k = 1;
int l = 0;
int[][] nums = new int[n][n];
int s = n;
while (s > 0) {
int i = l;
int j = l;
for(; j < n - l -1; j++) {
nums[i][j] = k;
k++;
}
for (; i < n - l - 1; i++) {
nums[i][j] = k;
k++;
}
for(; j > l; j--) {
nums[i][j] = k;
k++;
}
for(; i > l; i--) {
nums[i][j] = k;
k++;
}
s = s - 2;
l++;
}
if (n % 2 == 1) {
nums[n/2][n/2] = k++;
}
return nums;
}
}
总结
-
数组还是要灵活的注意双指针的使用。
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。





U8W/U8W-Mini使用与常见问题解决
QT多线程的5种用法,通过使用线程解决UI主界面的耗时操作代码,防止界面卡死。...
stm32使用HAL库配置串口中断收发数据(保姆级教程)
分享几个国内免费的ChatGPT镜像网址(亲测有效)
Allegro16.6差分等长设置及走线总结