本文主要是介绍代码随想录训练营第三十五期|第2天|数组part02|977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II ,总结,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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;}
}
这篇关于代码随想录训练营第三十五期|第2天|数组part02|977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II ,总结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!