977.有序数组的平方
题目链接:https://leetcode.cn/problems/squares-of-a-sorted-array/
思路
- 暴力解法,全部平方后Array.sort()。时间复杂度O(nlog n)
- 左右双指针。情况一:没有负数,数组元素小—>大;情况二:没有正数,数组元素大—>小;情况三:有正有负,数组元素大—>小—>大。情况一和情况二都是情况三的特殊情况,只有一个指针在移动。时间复杂度O(n)
代码
//两边向中间移动
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int[] res = new int[n];
if (nums[0] >= 0) {
for (int i = 0; i < n; i++) {
res[i] = nums[i] * nums[i];
}
return res;
}
int left = 0, right = n - 1;
int lastIndex = n - 1;
while (left <= right) {
if (nums[left] * nums[left] > nums[right] * nums[right]) {
res[lastIndex--] = nums[left] * nums[left];
left++;
} else {
res[lastIndex--] = nums[right] * nums[right];
right--;
}
}
return res;
}
}
209.长度最小的子数组
题目链接:https://leetcode.cn/problems/minimum-size-subarray-sum/
思路
采用滑动窗口,注意何时窗口要扩大,何时要缩小。时间复杂度O(n)
代码
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int sum = 0;//窗口内的值
int left = 0;
int minLen = nums.length + 1;
for (int right = 0; right < nums.length; right++) {
//窗口扩大,rigth移动
sum += nums[right];
while (sum >= target) {
//窗口缩小,更新长度,left移动
minLen = Math.min(right - left + 1, minLen);
sum -= nums[left++];
}
}
return minLen == nums.length + 1 ? 0 : minLen;
}
}
59.螺旋矩阵II
题目链接:https://leetcode.cn/problems/spiral-matrix-ii/
思路
按照示例图一步一步来就行了
代码
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int curNumber = 1;
while (curNumber <= n * n) {
for (int i = left; i <= right; i++) {
res[top][i] = curNumber++;
}
top++;
for (int i = top; i <= bottom; i++) {
res[i][right] = curNumber++;
}
right--;
for (int i = right; i >= left; i--) {
res[bottom][i] = curNumber++;
}
bottom--;
for (int i = bottom; i >= top; i--) {
res[i][left] = curNumber++;
}
left++;
}
return res;
}
}