class Solution {
public int[] sortedSquares(int[] nums) {
// 双指针问题, 左边的指针指向原数组的最左边
int left = 0;
// 右边的指针, 指向原数组的最右边
int right = nums.length - 1;
// 计算之后, 从新数组最右边开始写
int newIndex = nums.length - 1;
int[] result = new int[nums.length];
while (left <= right) {
if (nums[left] * nums[left] > nums[right] *nums[right]) {
result[newIndex] = nums[left] * nums[left];
left++;
newIndex--;
} else {
result[newIndex] = nums[right] *nums[right];
right--;
newIndex--;
}
}
return result;
}
}
class Solution {
public int minSubArrayLen(int target, int[] nums) {
// 滑动窗口, j是终止位置, i是起始位置, 从0开始
int i = 0;
int result = Integer.MAX_VALUE;
int sum = 0;
for (int j = 0; j < nums.length; j++) {
sum += nums[j];
while(sum >= target) {
// 更新子数组最小长度
result = Math.min(result, j - i + 1);
// 剔除左边界元素,尝试缩小子数组长度以找到长度更小的子数组
sum -= nums[i++];
}
}
// 如果result仍为初始值,说明没有找到满足条件的子数组,返回0;否则返回result
return result == Integer.MAX_VALUE ? 0 : result;
}
}
class Solution {
public int[][] generateMatrix(int n) {
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
int count = 1;
int target = n*n;
int[][] result = new int[n][n];
while(count <= target) {
// 从左到右填充,填充的列在[left,right]区间
for (int i = left; i <= right; i++) {
result[top][i] = count++;
}
// 缩小上边界
top++;
// 从上到下填充, 填充的行在[top,bottom]区间
for (int i = top; i <= bottom; i++) {
result[i][right] = count++;
}
// 缩小右边界
right--;
// 从右向左填充, 填充的行在[top,bottom]区间
for (int i = right; i >= left; i--) {
result[bottom][i] = count++;
}
// 缩小下边界
bottom--;
//从下向上填充, 填充的行在[bootom,top]区间
for(int i = bottom; i >= top; i--) {
result[i][left] = count++;
}
// 缩小左边界
left++;
}
return result;
}
}