今天的三题难度尚可,有思路了用不了太久就能AC。开始逐题总结。
原题链接:977 有序数组的平方
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
int i = 0, j = n - 1, idx = n - 1;
while (i <= j) {
if (nums[i] * nums[i] > nums[j] * nums[j]) {
ans[idx] = nums[i] * nums[i];
i++;
} else {
ans[idx] = nums[j] * nums[j];
j--;
}
idx--;
}
return ans;
}
}
本来用的是暴力做法如下:
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
ans[i] = nums[i] * nums[i];
}
Arrays.sort(ans);
return ans;
}
}
因为用了sort()方法,时间复杂度很明显为。看了解答以后很快也就能写出来双指针的解法。由于最大的数组元素一定会在原数组的两端取得,因此两个指针从原数组的两端往里边移动,比较完两者平方的大小以后填入答案数组。
原题链接:209 长度最小的子数组
此题一开始想到的是暴力解法,未能AC。滑动窗口可以很轻松的解决问题。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int start = 0, end = 0;
int sum = 0;
int ans = Integer.MAX_VALUE;
while (end <nums.length) {
sum += nums[end];
while (sum >= target) {
ans = Math.min(ans, end - start + 1);
sum -= nums[start];
start++;
}
end++;
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
}
看完代码即可理解思路,因此不再赘述。值得引起注意的是原题下面附加的要求时间复杂度在的解法。官方题解给出的是前缀和+二分查找的思路。附在下方。
class Solution {
public int minSubArrayLen(int s, int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int ans = Integer.MAX_VALUE;
int[] sums = new int[n + 1];
// 为了方便计算,令 size = n + 1
// sums[0] = 0 意味着前 0 个元素的前缀和为 0
// sums[1] = A[0] 前 1 个元素的前缀和为 A[0]
// 以此类推
for (int i = 1; i <= n; i++) {
sums[i] = sums[i - 1] + nums[i - 1];
}
for (int i = 1; i <= n; i++) {
int target = s + sums[i - 1];
int bound = Arrays.binarySearch(sums, target);
if (bound < 0) {
bound = -bound - 1;
}
if (bound <= n) {
ans = Math.min(ans, bound - (i - 1));
}
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
}
原题链接:59 螺旋矩阵II
本题可能是今天的三题中解答最顺利的一题。
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int count = 1;
while (count <= n * n) {
for (int i = left; i <= right; i++) {
ans[top][i] = count;
count++;
}
for (int i = top + 1; i <= bottom; i++) {
ans[i][right] = count;
count++;
}
for (int i = right - 1; i >= left; i--) {
ans[bottom][i] = count;
count++;
}
for (int i = bottom - 1; i > top; i--) {
ans[i][left] = count;
count++;
}
top++;
bottom--;
left++;
right--;
}
return ans;
}
}
值得注意的是解答过程中自己脑海中能够想象出一张螺旋矩阵的图出来(或者干脆照着官方题解的图来对照)。设置count计数器为循环的边界更容易理清思路(本来考虑的是while (top <= bottom && left <= right),后面发现将count从1循环到n^2更容易些)。每一圈填入数组元素以后将循环边界缩小即可。最终一次AC。