977. 有序数组的平方
代码随想录 (programmercarl.com)
本题要解决的核心问题在于,虽然数组是有序排列的,但是由于存在负数,如果求平方并不能确定其位置,所以还是需要使用到双指针,另外,由于结果要求升序排列,在填写输出数组时还要从后往前填
class Solution {
public int[] sortedSquares(int[] nums) {
int[] result = new int[nums.length];
int left = 0, right = nums.length - 1;
int res_index=nums.length - 1; //从后往前填写
while (left <= right) {
if(nums[left] * nums[left] <= nums[right] * nums[right]){
result[res_index--] = nums[right] * nums[right];
right--;
} else {
result[res_index--] = nums[left] * nums[left];
left++;
}
}
return result;
}
}
209. 长度最小的子数组
代码随想录 (programmercarl.com)
此题依然是双指针来解决,主要思想在于快指针探路,慢指针追赶
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int fast = 0, slow = 0;
int result = Integer.MAX_VALUE;
int sum = 0;
while (fast < nums.length) {
sum += nums[fast++];
while (sum >= target) {
result = (fast - slow) < result ? (fast - slow) : result;
sum -= nums[slow++];
}
}
if (result == Integer.MAX_VALUE) return 0;
return result;
}
}
59. 螺旋矩阵 II
代码随想录 (programmercarl.com)
着重点在于循环条件以及对于奇数的处理
class Solution {
public int[][] generateMatrix(int n) {
int nsquer = n * n;
int[][] result = new int[n][n];
int i = 0, j = 0;
int start = 0;
int insert = 1;
int loop = 0;
while (loop++ < n/2) { //循环条件
i = start;
j = start;
for ( ; j < n - loop; j++) {
result[i][j] = insert++;
}
for ( ; i < n - loop; i++) {
result[i][j] = insert++;
}
for ( ; j >= loop; j--) {
result[i][j] = insert++;
}
for ( ; i >= loop; i--) {
result[i][j] = insert++;
}
start++;
}
if (n % 2 == 1) { // n为奇数的处理
result[n/2][n/2] = insert;
}
return result;
}
}
网友评论