LeetCode 977-有序数组的平方
题目链接:
https://leetcode.cn/problems/squares-of-a-sorted-array/
解题思路:
-
暴力解法
将数组内元素求平方后用Arrays.sort()排序
-
双指针法
数组平方的最大值在数组的两端,所以左右各设一个指针进行比较,并从后往前赋值给result数组
代码实现
//暴力解法
class Solution {
public int[] sortedSquares(int[] nums) {
int len = nums.length;
for (int i = 0;i < len;i++) {
nums[i] *=nums[i];
}
Arrays.sort(nums);
return nums;
}
}
//双指针法
class Solution {
public int[] sortedSquares(int[] nums) {
int len = nums.length;
int i = 0,j = nums.length - 1;
int k = j;
int[] result = new int[nums.length];
while (i <= j) {
if (nums[i] * nums[i] < nums[j] * nums[j]) {
result[k--] = nums[j] * nums[j];
j--;
} else if (nums[i] * nums[i] >= nums[j] * nums[j]) {
result[k--] = nums[i] * nums[i];
i++;
}
}
return result;
}
}
难点:
暴力解法:
忘了Arrays.sort()递增排序
内容补充:
递减排序:Arrays.sort(intArray,Comparator.reverseOrder());
是Arrays而不是Array
双指针法:
while(i<=j) 为什么不是while(i<j)?
如果不考虑i = j的情况,则当i = j时直接退出循环,num中间的值被跳过,在result中没有num中间的平方值
LeetCode 209-长度最小的子数组
题目链接:
https://leetcode.cn/problems/minimum-size-subarray-sum/
解题思路:
-
滑动窗口
设置前后两个索引,j为终止索引,i为起始索引,随着j向后移动sum为子数组的和,当sum>=target时求出子数组元素个数,并与前一个最小元素数比较,i索引向后移动直到sum<target
代码实现
//滑动窗口
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int result = Integer.MAX_VALUE;
int i = 0;
int sum = 0;
for(int j = 0;j < nums.length;j++) {
sum += nums[j];
while (sum >= target) {
result = Math.min(j - i + 1,result);
sum -= nums[i++];
}
}
return result == Integer.MAX_VALUE?0:result;
}
}
难点:
- for循环中控制i的循环为什么要用while不用if
循环必须不断更新i的值,持续向后移动,从而更新滑动窗口大小,使sum<target
- 因为不确定传进的数组长度,所以result首先设置成Integer.MAX_VALUE;
- j - i + 1表示新子数组的长度,即后索引-前索引+1,而不是j - 1;
- 当sum > target时,要将前索引向后移动直到sum重新<target,即sum-=nums[i]