代码随想录打卡第二天|977.有序数组的平方209. 长度最小的子数组59. 螺旋矩阵 II(修订)
977. 有序数组的平方
//for循环
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0 , right = nums.length - 1;
int[] ans = new int[nums.length];
for(int i =ans.length-1 ; i >=0 ;i--){
int l = nums[left]*nums[left];
int r = nums[right]*nums[right];
if(l > r){
ans[i] = l;
left++;
}else{
ans[i] = r;
right--;
}
}
return ans;
}
}
//while循环
//左右指针,创建一个新数组,哪个指针指向的元素平方大,哪个放后面
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0 , right = nums.length - 1;
int[] ans = new int[nums.length];
//ans的计数器
int count = ans.length-1;
//为什么是小于等于,如果数组是单数,用<就会漏掉最中间的那个数
while(left <= right){
int l = nums[left]*nums[left];
int r = nums[right]*nums[right];
if(l > r){
ans[count--] = l;
left++;
}else{
ans[count--] = r;
right--;
}
}
return ans;
}
}
思路:左右指针
创建一个新数组,比较左右指针指向的元素平方后的大小,将大的数放入新数组中,最后返回数组
209. 长度最小的子数组
class Solution {
// 滑动窗口
public int minSubArrayLen(int s, int[] nums) {
int left = 0;
int sum = 0;
int result = Integer.MAX_VALUE;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= s) {
result = Math.min(result, right - left + 1);
sum -= nums[left++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
思路:设置滑动窗口,当结果大于大于目标值是,重新判断最小值
59. 螺旋矩阵 II
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
//转的圈数
int loop = 0;
//起始位置
int startX = 0;
int startY = 0;
int count = 1;
while(loop < n/2){
//左闭右开地遍历
while(startX < n-loop - 1){
ans[startY][startX] = count;
count++;
startX++;
}
while(startY < n-loop - 1){
ans[startY][startX] = count;
count++;
startY++;
}
while(startX > loop){
ans[startY][startX] = count;
count++;
startX--;
}
while(startY > loop){
ans[startY][startX] = count;
count++;
startY--;
}
loop++;
startX++;
startY++;
}
if(n%2 != 0){
ans[n/2][n/2] = count;
}
return ans;
}
}
思路:设置每次循环的边界