977. 有序数组的平方 - 力扣(LeetCode)
class Solution {public int[] sortedSquares(int[] nums) {int[] res = new int[nums.length];int idx = nums.length - 1;int left = 0;int right = nums.length - 1;while (left <= right) {if (nums[left] * nums[left] <= nums[right] * nums[right]) {res[idx] = nums[right] * nums[right];right--;idx--;} else {res[idx] = nums[left] * nums[left];left++;idx--;}}return res;}
}
209. 长度最小的子数组 - 力扣(LeetCode)
time: O(n)
Space:O(1)
class Solution {public int minSubArrayLen(int target, int[] nums) {int left = 0;int res = Integer.MAX_VALUE;int sum = 0;for (int right = 0; right < nums.length; right++) {sum += nums[right];while (sum - nums[left] >= target) {sum -= nums[left];left++;}if (sum >= target) res = Math.min(res, right - left + 1);}return res == Integer.MAX_VALUE ? 0 : res;}
}
第二种写法:把res的取值写道while循环里面
class Solution {public int minSubArrayLen(int target, int[] nums) {int left = 0;int res = Integer.MAX_VALUE;int sum = 0;for (int right = 0; right < nums.length; right++) {sum += nums[right];while (sum >= target) {res = Math.min(res, right - left + 1);sum -= nums[left];left++;}}return res == Integer.MAX_VALUE ? 0 : res;}
}
59. 螺旋矩阵 II - 力扣(LeetCode)
loop++放在后面就会不过,为什么呢
class Solution {public int[][] generateMatrix(int n) {int start = 0;int loop = 0;int count = 1;int[][] res = new int[n][n];int i;int j;while (loop++ < n/2) {//left->rightfor (j = start; j < n - loop; j++) {res[start][j] = count++;}//right side up to downfor (i = start; i < n - loop; i++) {res[i][j] = count++;}//down right to leftfor (; j >= loop; j--) {res[i][j] = count++;}//left side down to upfor (; i >= loop; i--) {res[i][j] = count++;}start++;//loop++;}if (n % 2 == 1) {res[start][start] = count;}return res;}
}