977.有序数组的平方
双指针,空间换时间,最大值肯定在头尾,原数组头尾两个指针比较大小,在开辟新的数组从后往前填入,一直纠结如何原地判断,浪费了很多时间。
class Solution {
public static int square(int number) {
return number * number;
}
public int[] sortedSquares(int[] nums) {
int high = nums.length - 1;
int low = 0;
int[] array = new int[nums.length];
int k = high;
while (low <= high) {
if (square(nums[low]) < square(nums[high])) {
array[k] = square(nums[high]);
k--;
high--;
} else if (square(nums[low]) >= square(nums[high])) {
array[k] = square(nums[low]);
k--;
low++;
}
}
return array;
}
}
209.长度最小子数组
这个采用滑动窗口,外层for循环判断尾指针,内层while循环不断删除窗口前端的值,并且更新最短序列长度,内层while是精髓,动态调节。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int sum = 0;
int len = 0;
int left = 0;
int result = nums.length + 1;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
len++;
while (sum >= target) {
result=Math.min(result,len);
sum -= nums[left];
left++;
len--;
}
}
return result == nums.length + 1 ? 0 : result;
}
}
三元运算符
return bool ? a : b ;
bool为true返回a,否则返回b。
59.螺旋矩阵二
找循环不变量,一圈一圈的生成。
总共需要填几圈由外层while的n/2决定,每圈的每条边需要填写的个数n - (epoch - 1) * 2 - 1,如果是奇数的n需要在最后的矩阵中心额外填写一次。
class Solution {
public int[][] generateMatrix(int n) {
int[][] array = new int[n][n];
int start_x = 0;
int start_y = 0;
int epoch = 1;
int num = 1;
while (epoch <= n / 2) {
for (int j = 0; j < n - (epoch - 1) * 2 - 1; start_y++, num++) {
array[start_x][start_y] = num;
j++;
}
for (int j = 0; j < n - (epoch - 1) * 2 - 1; start_x++, num++) {
array[start_x][start_y] = num;
j++;
}
for (int j = 0; j < n - (epoch - 1) * 2 - 1; start_y--, num++) {
array[start_x][start_y] = num;
j++;
}
for (int j = 0; j < n - (epoch - 1) * 2 - 1; start_x--, num++) {
array[start_x][start_y] = num;
j++;
}
start_x++;
start_y++;
epoch++;
}
if (n % 2 == 1) {
int i = n / 2;
array[i][i] = n * n;
}
return array;
}
}
//runtime:0 ms
//memory:40.4 MB