题目链接:977. 有序数组的平方 - 力扣(LeetCode)
class Solution {
public int[] sortedSquares(int[] nums) {
int[] arr = new int[nums.length];
int left = 0;
int right = nums.length - 1;
int i = nums.length - 1;
while(left <= right){
if(nums[left] * nums[left] < nums[right] * nums[right]){
arr[i] = nums[right] * nums[right];
i--;
right--;
}else{
arr[i] = nums[left] * nums[left];
i--;
left++;
}
}
return arr;
}
}
暴力解法:每个数平方之后用快排
进阶解法:双指针,因为给出的数组是非递减顺序,所以平方后最大的数一定在两头,两个指针一头一尾,慢慢向中间逼近。
题目链接:209. 长度最小的子数组 - 力扣(LeetCode)
lass Solution {
public int minSubArrayLen(int target, int[] nums) {
int i = 0;
int result = nums.length;
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++];
}
}
if (i == 0 && sum < target){
return 0;
}
return result;
}
}
双指针,后面的指针先往后走,达到要求之后前面的指针再往后缩进。
题目链接:59. 螺旋矩阵 II - 力扣(LeetCode)
class Solution {
public int[][] generateMatrix(int n) {
int loop = 1;
int startx = 0;
int starty = 0;
int i, j;
int number = 1;
int[][] result = new int[n][n];
while(loop <= n/2){
for(j = starty; j < (n - loop); j ++){
result[startx][j] = number ++;
}
for(i = startx; i < (n - loop); i ++){
result[i][j] = number ++;
}
for( ; j > starty; j --){
result[i][j] = number ++;
}
for( ; i > startx; i --){
result[i][j] = number ++;
}
loop ++;
startx ++;
starty ++;
}
if (n % 2 == 1){
result[startx][starty] = number;
}
return result;
}
}
主要注意以什么来循环,区间,左开右闭,以及n为基数还是偶数。