题目链接
思路:数组是有序的,平方后最大值只会出现在数组两端,因此可以使用双指针法从两端选取最大值放在新数组的尾部。
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0, right = nums.length - 1, i = right;
int[] result = new int[nums.length];
while (left <= right) {
int a = nums[left] * nums[left];
int b = nums[right] * nums[right];
if (a > b) {
result[i--] = a;
left++;
}else {
result[i--] = b;
right--;
}
}
return result;
}
}
题目链接
思路:滑动窗口是不断调节子序列的起始位置和终止位置,从而得到我们想要的结果,for循环是右边界,当区间值大于等于target时就要移动左边界,边移动边记录,直到小于。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0, sum = 0, min = Integer.MAX_VALUE, len = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
while (sum >= target) {
len = i - left + 1;
min = Math.min(min, len);
sum -= nums[left++];
}
}
return min == Integer.MAX_VALUE ? 0 : min;
}
}
题目链接:
思路:
class Solution {
public int totalFruit(int[] fruits) {
Map<Integer, Integer> map = new HashMap<>();
int left = 0, max = 0;
for (int i = 0; i < fruits.length; i++) {
map.put(fruits[i], map.getOrDefault(fruits[i], 0) + 1);
while (map.size() > 2) {
map.put(fruits[left], map.get(fruits[left]) - 1);
if (map.get(fruits[left]) == 0) {
map.remove(fruits[left]);
}
left++;
}
max = Math.max(max, i - left + 1);
}
return max;
}
}
题目链接
思路:确定循环不变量,左闭右开,然后模拟过程
class Solution {
public int[][] generateMatrix(int n) {
int k = 1;
int[][] nums = new int[n][n];
for (int i = 0; i <= n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
nums[i][j] = k++;
}
for (int j = i; j < n - i - 1; j++) {
nums[j][n-i-1] = k++;
}
for (int j = n - i - 1; j > i; j--) {
nums[n-i-1][j] = k++;
}
for (int j = n - i - 1; j > i; j--) {
nums[j][i] = k++;
}
}
if (n % 2 == 1) nums[n/2][n/2] = k;
return nums;
}
}