- leetcode 977 有序数组的平方 easy
题目链接: leetcode.com/problems/sq…
思路: 有序数组两头可能出现最大值,左侧是因为包含负数,因此只需设定左右指针,让左右指针所在位置进行打擂台,就可以不断选出较大的值,依次从后面放入新数组空间即可。
代码:
class Solution {
public int[] sortedSquares(int[] nums) {
int[] newArray = new int[nums.length];
int left = 0;
int right = nums.length - 1;
int idx = newArray.length - 1;
while (left <= right) {
if (nums[left] * nums[left] > nums[right] * nums[right]) {
newArray[idx--] = nums[left] * nums[left];
left++;
} else {
newArray[idx--] = nums[right] * nums[right];
right--;
}
}
return newArray;
}
}
提交报错 (1):
第1次: 写代码时专注于整体思路,反而忽略了平方比较才有意义,数组长度不减1就作为下标用于数组取值,都属于低级错误。
- leetcode 209 长度最小的子数组 medium
题目链接: leetcode.com/problems/mi…
思路: 双指针题型的头尾指针解法(滑动窗口),先移动尾指针直到符合题目检索要求(扩大窗口-通过扩大范围寻找最优解),再移动头指针到不符合题目要求(减小窗口-通过缩减范围寻找最优解)。
代码:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int start = 0;
int sum = 0;
int len = 0;
int result = Integer.MAX_VALUE;
for (int end = 0; end < nums.length; end++) {
sum += nums[end];
while (sum >= target) {
len = end - start + 1;
result = len < result ? len : result;
sum -= nums[start++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
提交报错 (2):
第1次: 结果错误。 输出2, 期待输出是1. 原因是没想清楚如何计算最小子数组长度,即。
第2次: 结果错误。 输出0, 期待输出是1. 每次更新窗口大小(长度)如何与已保存最优解比较更新,在什么位置比较更新都很模糊,答案是只要窗口变化就要计算长度并选出最优解
- leetcode 59 螺旋矩阵II medium
题目链接: leetcode.com/problems/sp…
关键点: 最关键还是想好每一轮循环的起始点和结束点。offset和每轮循环的关系也需考虑清楚。
代码:
class Solution {
public int[][] generateMatrix(int n) {
int count = 1;
int loop = 0;
int offset = 1;
int[][] matrix = new int[n][n];
int i, j;
while (loop < n/2) {
for (j = loop; j < n - offset - loop; j++) {
matrix[loop][j] = count++;
}
for (i = loop; i < n - offset - loop; i++) {
matrix[i][j] = count++;
}
for (; j > loop; j--) {
matrix[i][j] = count++;
}
for (; i > loop; i--) {
matrix[i][j] = count++;
}
loop++;
}
if (n % 2 == 1) {
matrix[loop][loop] = count;
}
return matrix;
}
}
提交报错 (1):
第1次: 没有先定义行列而导致报错