977.有序数组的平方
https://leetcode.cn/problems/squares-of-a-sorted-array/description/
public static int[] sortedSquares(int[] nums){
int left = 0;
int right = nums.length - 1;
int[] result = new int[nums.length];
int write = result.length - 1;
while (left <= right){
if (Math.pow(nums[left],2) > Math.pow(nums[right],2)) {
result[write] = nums[left] * nums[left];
left++;
write--;
}else {
result[write] = nums[right] * nums[right];
right--;
write--;
}
}
return result;
}
总结:双指针每次在最大的两个之中去读,把大的添加到新数组中
** 209.长度最小的子数组**
https://leetcode.cn/problems/minimum-size-subarray-sum/description/
public static int minSubArrayLen(int target, int[] nums) {
int left = 0;
int sum = 0;
int result = Integer.MAX_VALUE;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target){
result = Math.min(result,right - left +1);
sum -= nums[left++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
总结:滑动窗口的思想,right仅需一次遍历数组即可,right一直向前,无需回头
59.螺旋矩阵II
https://leetcode.cn/problems/spiral-matrix-ii/submissions/508708830/
public static int[][] generateMatrix(int n) {
int l = 0,t = 0,r = n - 1,b = n - 1;
int num = 1 , tar = n * n;
int[][] result = new int[n][n];
while (num <= tar){
for (int i = l; i <= r; i++) {
result[t][i] = num++;
}
t++;
for (int i = t; i <= b; i++){
result[i][r] = num++;
}
r--;
for (int i = r; i >= l; i--){
result[b][i] = num++;
}
b--;
for (int i = b; i >= t; i--){
result[i][l] = num++;
}
l++;
}
return result;
}
总结:这种矩阵的题 关键就在于 上下左右四个边界定义好,定义好之后边界就包含了遍历的下标的信息,之后边界一直在变,就往里填数字就好,关键就在于边界!!!
标签:977,right,nums,int,随想录,--,result,数组,left From: https://www.cnblogs.com/jeasonGo/p/18058596