977.有序数组的平方
代码示例
lass Solution {
public int[] sortedSquares(int[] nums) {
int k = nums.length - 1;
int[] result = new int[nums.length];
for (int i = 0, j = nums.length - 1;i <= j;){
if (nums[i]*nums[i] > nums[j]*nums[j]) {
result[k--] = nums[i]*nums[i];
i++;
} else if (nums[i]*nums[i] == nums[j]*nums[j]) {
result[k--] = nums[j]*nums[j];
j--;
} else {
result[k--] = nums[j]*nums[j];
j--;
}
}
return result;
}
}
心得体会
利用双指针从数组两头开始遍历数组,由于原数组两头的元素一定是新数组较大元素,因此先找两头进行比较,并在每次比较后,将较大的元素位置移动一格,再与另一侧元素进行比较……(有点类似冒泡排序)。
209.长度最小的子数组
代码示例
class Solution {
public int minSubArrayLen(int s, int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int ans = Integer.MAX_VALUE;
int[] sums = new int[n + 1];
for (int i = 1; i <= n; i++) {
sums[i] = sums[i - 1] + nums[i - 1];
}
for (int i = 1; i <= n; i++) {
int target = s + sums[i - 1];
int bound = Arrays.binarySearch(sums, target);
if (bound < 0) {
bound = -bound - 1;
}
if (bound <= n) {
ans = Math.min(ans, bound - (i - 1));
}
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
}
心得体会
首先,创建一个长度为n + 1的前缀和数组sums,其中sums[i]表示nums数组中前i个元素的和。然后,遍历数组nums并计算前缀和。接下来,遍历数组nums并计算每个子数组的和。对于每个子数组,计算目标值target,该值等于s加上前i-1个元素的和。然后,使用Arrays.binarySearch方法在sums数组中查找target。如果找到了target,则计算子数组的长度,并将其与当前最小长度进行比较。如果没有找到target,则使用返回的插入点计算子数组的长度,并将其与当前最小长度进行比较。最后,返回最小长度。
59.螺旋矩阵 ||
代码分析
class Solution {
public int[][] generateMatrix(int n) {
int loop = 0;
int[][] res = new int[n][n];
int start = 0;
int count = 1;
int i, j;
while (loop++ < n / 2) {
// 上侧从左到右
for (j = start; j < n - loop; j++) {
res[start][j] = count++;
}
// 右侧从上到下
for (i = start; i < n - loop; i++) {
res[i][j] = count++;
}
// 下侧从右到左
for (; j >= loop; j--) {
res[i][j] = count++;
}
// 左侧从下到上
for (; i >= loop; i--) {
res[i][j] = count++;
}
start++;
}
if (n % 2 == 1) {
res[start][start] = count;
}
return res;
}
}
心得体会
代码中的loop变量控制循环次数,每次循环填充一圈数字。start变量表示每次循环的起始点,初始值为0。count变量表示当前填充的数字,初始值为1。四个循环分别模拟从上到下、从左到右、从下到上、从右到左四个方向的填充过程。每次填充一个数字后,更新起始点和计数器。最后,如果n为奇数,则在中心位置填充最后一个数字。