lc209长度最小的数组
思路
- 双指针实现较低的时间复杂度
- 终止节点不断遍历,达到目标和进行窗口收缩
代码
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int minLen = Integer.MAX_VALUE;
int left = 0;
int sum = 0;
for (int right = 0; right < nums.length; right++){
sum += nums[right];
while (sum >= target){
minLen = Math.min(right-left+1, minLen);
sum -= nums[left];
left++;
}
}
return minLen == Integer.MAX_VALUE ? 0 : minLen;
}
}
lc59螺旋矩阵II
思路
- 确定循环次数、循环不变量
- 确定四条边遍历时的下标
- 判断是否存在中心点
代码
class Solution {
public int[][] generateMatrix(int n) {
int loop = n / 2, val = 1;
int[][] res = new int[n][n];
int i,j,start = 0;
for (int k = 1; k <= loop; k++){
for (j = start; j < n-k; j++){
res[start][j] = val++;
}
for (i = start; i < n-k; i++){
res[i][j] = val++;
}
for (; j > start; j--){
res[i][j] = val++;
}
for (; i > start; i--){
res[i][j] = val++;
}
start++;
}
if (n%2 != 0){ res[n/2][n/2]=val; }
return res;
}
}