力扣题977:有序数组的平方(双指针法)
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
示例 1:
- 输入:nums = [-4,-1,0,3,10]
- 输出:[0,1,9,16,100]
- 解释:平方后,数组变为 [16,1,0,9,100],排序后,数组变为 [0,1,9,16,100]
class Solution {
public int[] sortedSquares(int[] nums) {
//结果数组
int res[] = new int[nums.length];
int k = nums.length - 1;
//用双指针法
for(int i = 0,j = nums.length - 1; i <= j;){
if(nums[i]*nums[i] <= nums[j]*nums[j]){
res[k] = nums[j]*nums[j];
k--;
j--;
} else{
res[k] = nums[i]*nums[i];
k--;
i++;
}
}
return res;
}
}
力扣题209:长度最小的子数组
滑动窗口(重点在于如何移动起始位置)
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
示例:
- 输入:s = 7, nums = [2,3,1,2,4,3]
- 输出:2
- 解释:子数组 [4,3] 是该条件下的长度最小的子数组。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int start = 0; //定义滑动窗口的初始位置
int sum = 0;
int subL = 0; //定义滑动窗口的长度
int res = nums.length + 1; //初始化当前数组的长度
for(int end = 0; end < nums.length; end++){
sum += nums[end];
while(sum >= target){
subL = end - start + 1;
res = Math.min(res,subL);
sum = sum - nums[start];
start++;
}
}
return res == nums.length+1 ? 0 : res;
}
}
力扣题59:螺旋矩阵
给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int startx = 0, starty = 0;//定义每一圈的起始位置
int offset = 1; //定义变量来控制终止位置
int count = 1;//要插入的元素
int loop = 1; //当前的圈数
int i,j;//多少行,多少列
while(loop <= n/2){
//上边
for(j = starty; j < n-offset; j++){
res[startx][j] = count++;
}
//右边
for(i = startx; i < n-offset; i++){
res[i][j] = count++;
}
//下边
for(;j > starty;j--){
res[i][j] = count++;
}
//左边
for(; i > startx; i--){
res[i][j] = count++;
}
startx++;
starty++;
loop++;
offset++;
}
if(n%2 == 1){
res[startx][starty] = n*n;
}
return res;
}
}