有序数组的平方
看完题目直接写了一个最简单的解法
class Solution {
public int[] sortedSquares(int[] nums) {
for (int i = 0; i < nums.length; i++) {
nums[i] = nums[i] * nums[i];
}
Arrays.sort(nums);
return nums;
}
}
但是这种解法时间复杂度不符合题目要求,想到了昨天的双指针,写了一个满足条件的双指针版本
class Solution {
public int[] sortedSquares(int[] nums) {
int[] res = new int[nums.length];
int l = 0, r = nums.length - 1, k = nums.length - 1;
for (; l <= r; ) {
if(nums[l] * nums[l] > nums[r] * nums[r]) {
res[k] = nums[l] * nums[l];
l++;
} else {
res[k] = nums[r] * nums[r];
r--;
}
k--;
}
return res;
}
}
长度最小的子数组
读完题知道这是滑动窗口,但是太长时间没用过了,依稀记得以前学的时候老师告诉我是固定右端点,然后不断调整左端点。但是写了半天还是没过,最后看了卡哥的题解,发现了错误点,改正记录。
ps:这道题还要注意它存在不符合条件的子数组,最开始没特判这种情况返回值直接错了。。。。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int size = nums.length;
int res = Integer.MAX_VALUE; //判断值
int sum = 0;
int l = 0;
for(int r = 0; r < size; r++) { //移动右端点
sum += nums[r];
while(sum >= target) {
res = Math.min(res, r - l + 1);
sum -= nums[l];
l ++; //左端点向前推进
}
}
return res == Integer.MAX_VALUE? 0: res; //注意题目条件 特判
}
}
螺旋矩阵
模拟题,但是边界处理真的很折磨
看了题解之后自己写了一遍,需要注意的点就是循环几次和循环条件的问题,画图可以更好理解
class Solution {
public int[][] generateMatrix(int n) {
int loop = 0;
int start = 0;
int count = 1;
int[][] res = new int[n][n];
int i, j;
while (loop++ < n / 2) {
for (j = start; j < n - loop; j++) {
res[start][j] = count++;
}
for (i = start; i < n - loop; i++) {
res[i][j] = count++;
}
for(; j >= loop; j--) {
res[i][j] = count++;
}
for(; i >= loop; i--) {
res[i][j] = count++;
}
start++;
}
if(n % 2 == 1) {
res[start][start] = count;
}
return res;
}
}