题目
977. Squares of a Sorted Array
209. Minimum Size Subarray Sum
59. Spiral Matrix II
977. Squares of a Sorted Array
class Solution {
public int[] sortedSquares(int[] nums) {
int[] res = new int[nums.length];
int left = 0;
int right = nums.length - 1;
for (int i = nums.length - 1; i >= 0; i--) {
if (Math.abs(nums[left]) >= Math.abs(nums[right])) {
res[i] = nums[left] * nums[left];
left++;
} else {
res[i] = nums[right] * nums[right];
right--;
}
}
return res;
}
}
//time: O(n)
//space: O(1)
209. Minimum Size Subarray Sum
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int res = Integer.MAX_VALUE;
int left = 0;
int right = 0;
int sum = nums[0];
while (right < nums.length) {
if (sum < target) {
right++;
if (right < nums.length) {
sum += nums[right];
}
} else {
res = Math.min(right - left + 1, res);
sum -= nums[left];
left++;
}
}
return res == Integer.MAX_VALUE? 0 : res;
}
}
//Time: O(n), the left and right pointer at most move n steps. n is the length of nums
//Space: O(1)
59. Spiral Matrix II
写的是自己看完题后第一思路的解答。其中的四个小while循环可以优化成for循环,同时减少x和y的维护。但是个人还是更习惯维护上下左右四个边界。
在最外层循环的时候考虑了n为1的情况,认为限制条件应该是left <= right && top <= bottom。
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int num = 1;
int x = 0;
int y = 0;
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
while (left <= right && top <= bottom) {
while (y <= right) {
res[x][y++] = num++;
System.out.println(x);
System.out.println(y - 1);
System.out.println(num - 1);
}
y--;
top++;
x = top;
while (x <= bottom) {
res[x++][y] = num++;
System.out.println(x - 1);
System.out.println(y);
System.out.println(num - 1);
}
x--;
right--;
y = right;
while (y >= left) {
res[x][y--] = num++;
System.out.println(x);
System.out.println(y + 1);
System.out.println(num - 1);
}
y++;
bottom--;
x = bottom;
while (x >= top) {
res[x--][y] = num++;
System.out.println(x + 1);
System.out.println(y);
System.out.println(num - 1);
}
x++;
left++;
y = left;
}
return res;
}
}