一、LC977.有序数组的平方
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
双指针法,设置一左一右两个指针,从数组两端开始遍历。因为数组是非递减,所以平方最大值产生在数组最左或者最右。将元素从大到小加入数组中。
视频讲解:双指针法经典题目 | LeetCode:977.有序数组的平方_哔哩哔哩_bilibili
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int[] result = new int[nums.length];
int index = nums.length - 1;
while (left <= right){
if (nums[left] * nums[left] < nums[right] * nums[right]) {
result[index--] = nums[right] * nums[right];
right -= 1;
} else {
result[index--] = nums[left] * nums[left];
left += 1;
}
}
return result;
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(n)
二、LC209.长度最小的子数组
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
视频讲解:拿下滑动窗口! | LeetCode 209 长度最小的子数组_哔哩哔哩_bilibili
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int len = 0;
int total = 0;
int start = 0;
for (int i = 0; i < nums.length; i++) {
total += nums[i];
//System.out.println(i + " " + total);
while (total >= target) {
if (len == 0) {
len = i - start + 1;
} else {
len = Math.min(len, i - start + 1);
}
total -= nums[start];
start += 1;
}
}
return len;
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(1)
一些录友会疑惑为什么时间复杂度是O(n)。
不要以为for里放一个while就以为是O(n^2)啊, 主要是看每一个元素被操作的次数,每个元素在滑动窗后进来操作一次,出去操作一次,每个元素都是被操作两次,所以时间复杂度是 2 × n 也就是O(n)
三、LC59.螺旋矩阵II
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
视频讲解:一入循环深似海 | LeetCode:59.螺旋矩阵II_哔哩哔哩_bilibili
class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int top = 0;
int bottom = n-1;
int left = 0;
int right = n-1;
int num = 1;
while (num <= n*n) {
for (int i = left; i < right + 1; i++) {
result[top][i] = num;
num++;
}
for (int j = top + 1; j < bottom + 1; j++) {
result[j][right] = num;
num++;
}
for (int k = right - 1; k >= left; k--) {
result[bottom][k] = num;
num++;
}
for (int m = bottom - 1; m > top; m--) {
result[m][left] = num;
num++;
}
left += 1;
right -= 1;
top += 1;
bottom -= 1;
}
return result;
}
}
- 时间复杂度:O(n^2)
- 空间复杂度:O(n^2)