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;
}
總結:這種矩陣的題 關鍵就在於 上下左右四個邊界定義好,定義好之後邊界就包含了遍歷的下標的資訊,之後邊界一直在變,就往裡填數字就好,關鍵就在於邊界!!!