977.有序数组的平方
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
示例 1: 输入:nums = [-4,-1,0,3,10] 输出:[0,1,9,16,100] 解释:平方后,数组变为 [16,1,0,9,100],排序后,数组变为 [0,1,9,16,100]
示例 2: 输入:nums = [-7,-3,2,3,11] 输出:[4,9,9,49,121]
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int[] ans = new int[nums.length];
int idx = nums.length - 1;
while (left <= right) {
if (nums[left] * nums[left] >= nums[right] * nums[right]) {
ans[idx] = nums[left] * nums[left];
left++;
} else {
ans[idx] = nums[right] * nums[right];
right--;
}
idx--;
}
return ans;
}
209.长度最小的子数组
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
示例:
输入:s = 7, nums = [2,3,1,2,4,3] 输出:2 解释:子数组 [4,3] 是该条件下的长度最小的子数组。
class Solution {
// [2,3,1,2,4,3]
public int minSubArrayLen(int target, int[] nums) {
int ans = Integer.MAX_VALUE;
int left = 0;
int right = 0;
int sum = 0;
for (; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) {
ans = Math.min(ans, right - left + 1);
sum -= nums[left];
left++;
}
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
}
滑动窗口,窗口尾巴依次动,整个窗口中的值>=targrt(坑,不是=)时,窗口脑袋右移,移动过程中记录最短的个数。开始想法移动头,在每一个头处依次遍历数组求>=target的最少个数,时间复杂度O(n^2),超时了。
59.螺旋矩阵
给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution {
public int[][] generateMatrix(int n) {
int c1 = 0, c2 = n - 1;
int r1 = 0, r2 = n - 1;
int[][] ans = new int[n][n];
int num = 1;
while (c1 <= c2 && r1 <= r2) {
for (int i = c1; i <= c2; i++) {
ans[r1][i] = num;
num++;
}
for (int i = r1 + 1; i <= r2; i++) {
ans[i][c2] = num;
num++;
}
for (int i = c2 - 1; i >= c1; i--) {
ans[r2][i] = num;
num++;
}
for (int i = r2 - 1; i > r1; i--) {
ans[i][c1] = num;
num++;
}
r1++;
r2--;
c1++;
c2--;
}
return ans;
}
}
模拟,挺麻烦的,下次遇到这种纯模拟题也不知道写得出来写不出来