977
java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 2 at line 17, Solution.sortedSquares at line 54, DriverSolution.helper at line 84, Driver.main
最开始的代码如下,但报错
class Solution {
public int[] sortedSquares(int[] nums) {
int len = nums.length;
int left = 0;
int right = len - 1;
int newArrPos = len - 1;
int[] result = new int[len];
if (len == 1) {
result[0] = nums[0] * nums[0];
return result;
}
while (left <= right) {
if (Math.abs(nums[left]) <= Math.abs(nums[right])) {
result[newArrPos--] = (nums[right] * nums[right]);
right--;
}
if (Math.abs(nums[left]) > Math.abs(nums[right])) {
result[newArrPos--] = (nums[left] * nums[left]);
left++;
}
}
return result;
}
}
排查发现逻辑判断没有短路,两个if都进入造成越界 修改后代码如下
class Solution {
public int[] sortedSquares(int[] nums) {
int len = nums.length;
int left = 0;
int right = len - 1;
int newArrPos = len - 1;
int[] result = new int[len];
if (len == 1) {
result[0] = nums[0] * nums[0];
return result;
}
while (left <= right) {
if (Math.abs(nums[left]) <= Math.abs(nums[right])) {
result[newArrPos--] = (nums[right] * nums[right]);
right--;
}
else if (Math.abs(nums[left]) > Math.abs(nums[right])) {
result[newArrPos--] = (nums[left] * nums[left]);
left++;
}
}
return result;
}
}
209长度最小的子数组
暴力算法超时
思考 找到最大值,从最大值向两边搜索,但应该不行 实在想不出来,看解析
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int length = nums.length;
int result = Integer.MAX_VALUE;
int i = 0; //滑动窗口的起始位置
int sum = 0;
for (int j = 0; j < length; j++) {
sum += nums[j]; //先选出初时窗口长度
while (sum >= target) {
int distance = j - i + 1;
result =distance < result ? distance : result;
sum -= nums[i++]; //开始滑动
}
}
if (result == Integer.MAX_VALUE) {
return 0;
}
return result;
}
}
非常精妙的动态窗口,开始进不去while循环,在for循环中选出初始窗口(即和大于目标值的), 然后记录当前长度,然后窗口缩小(即左边界缩小,在while中),缩小后如果还是满足,则左窗口继续缩小。 如果不满足,则跳出while循环,进入下一次for循环(即j++,右边界扩大)
59 螺旋矩阵2
注意控制不变量
注意固定左闭右开,或者左开右闭
class Solution {
public int[][] generateMatrix(int n) {
int[][] array = new int[n][n];
int loop = 0; //循环次数
int start = 0; //开始点
int num = 1;
int i, j;
//循环一圈少两个数字
while (loop++ < (n / 2)) {
//上方从左到右
for (j = start; j < n - loop; j++) {
array[start][j] = num++;
}
//右方从上到下
for (i = start; i < n - loop; i++) {
array[i][j] = num++;
}
//下方从右到左
for (; j >= loop; j--) {
array[i][j] = num++;
}
//左方从下到上
for (; i >= loop; i--) {
array[i][j] = num++;
}
start++;
}
if (n % 2 != 0) {
array[start][start] = n * n;
}
return array;
}
}