977.有序数组的平方
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
输入:nums = [-4,-1,0,3,10]
输出:[0,1,9,16,100]
数组是有序的, 只不过负数平方之后可能成为最大数了。
那么数组平方的最大值在数组的两端,不是最左边就是最右边,不可能是中间。
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length-1;
int[] result = new int[nums.length];
int index = result.length-1;
while(left <= right){
if(nums[left] * nums[left] > nums[right] * nums[right]){
result[index--] = nums[left] * nums[left];
++left;
}else{
result[index--] = nums[right] * nums[right];
--right;
}
}
return result;
}
}
209.长度最小的子数组
给定一个含有 n 个正整数的数组和一个正整数 target 。找出该数组中满足其元素和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
👉🏻窗口 : 满足其元素和 ≥ s 的长度最小的连续子数组。
👉窗口起始位置如何移动:当前窗口的值大于s,窗口就要向前移动了(也就是该缩小了)。
class Solution {
public 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;
}
}
59.螺旋矩阵II
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
👉🏻循环不变量 : 区间 左闭右开
- 填充上行从左到右
- 填充右列从上到下
- 填充下行从右到左
- 填充左列从下到上
输入: n = 3
输出: [[1,2,3],[8,9,4],[7,6,5]]
class Solution {
public int[][] generateMatrix(int n) {
int[][]arr = new int[n][n];
int loop = 0;
int start = 0;
int count = 1;
int i,j;
while(loop++ < n / 2){
for(j = start; j < n-loop; j++){
arr[start][j] = count++;
}
for(i = start; i < n-loop; i++){
arr[i][j] = count++;
}
for( ;j >= loop; j--){
arr[i][j] = count++;
}
for( ;i >= loop; i--){
arr[i][j] = count++;
}
start++;
}
if(n%2 == 1){
arr[start][start] = count;
}
return arr;
}
}
开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 2 天,点击查看活动详情”