有序数组的平方
双指针应用
题目:LeetCode.977
class Solution {
public int[] sortedSquares(int[] nums) {
int i = 0;
int j = nums.length - 1;
int[] arr = new int[nums.length];
int k = arr.length - 1;
while(i <= j){
if(nums[i] * nums[i] >= nums[j] * nums[j]){
arr[k--] = nums[i] * nums[i];
i++;
}
else{
arr[k--] = nums[j] * nums[j];
j--;
}
}
return arr;
}
}
长度最小子数组
题目:LeetCode.209
写法1:暴力解法
写法2:滑动窗口
所谓滑动窗口 ,就是不断的调节子序列的起始位置和终止位置,从而得出我们想要的结果。
关键在于如何移动窗口的起始位置。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int i = 0;
int sum = 0;
int cnt = Integer.MAX_VALUE;//输出个数
for (int j = 0 ; j < nums.length ; j++) {
sum += nums[j];
while (sum >= target){
cnt = Math.min(cnt,j - i + 1);
sum -= nums[i++];
}
}
return cnt == Integer.MAX_VALUE ? 0:cnt;
}
}
螺旋矩阵
注意循环不变量
class Solution {
public int[][] generateMatrix(int n) {
int[][] arr = new int[n][n];
int cnt = 2;//循环次数
int start = 0;//起始位置
int val = 1;
int i,j;
while(cnt <= n){
for(j = start ; j < n - cnt / 2 ; j++){
arr[start][j] = val++;
}
for(i = start ; i < n - cnt / 2 ; i++){
arr[i][j] = val++;
}
for(; j >= cnt / 2 ; j--){
arr[i][j] = val++;
}
for(; i >= cnt / 2 ; i--){
arr[i][j] = val++;
}
start++;
cnt+=2;
}
if (n % 2 == 1) {
arr[start][start] = val;
}
return arr;
}
}