977.有序数组的平方
leetcode题目链接:https://leetcode.cn/problems/squares-of-a-sorted-array
leetcode AC记录:
解题思路:
1.将数组分为大于等于0和小于0的两组,记录两组分割的下标
2.对两组下标进行归并排序,负数数组平方后大小变换位置,从后往前;正数则不变;
代码如下:
class Solution {
public int[] sortedSquares(int[] nums) {
//排除特殊情况
if(nums.length <= 0) {
return nums;
}
int[] res = new int[nums.length];
//初始化activeBegin 和 negativeEnd
int activeBegin = Integer.MAX_VALUE;
int negativeEnd = -1;
for(int i = 0;i < nums.length;i++) {
if(nums[i] < 0) {
negativeEnd = i;
}
if(nums[i] >= 0 && activeBegin == Integer.MAX_VALUE) {
activeBegin = i;
}
}
mergeArr(res, nums, activeBegin, negativeEnd);
return res;
}
/**
* 归并正负数组,negative
*/
public void mergeArr(int[] res, int[] nums, int activeBegin, int negativeEnd) {
int totalIndex = 0;
while(activeBegin < nums.length && negativeEnd >= 0) {
if(nums[activeBegin] * nums[activeBegin] <= nums[negativeEnd] * nums[negativeEnd]) {
res[totalIndex++] = nums[activeBegin] * nums[activeBegin];
activeBegin++;
} else {
res[totalIndex++] = nums[negativeEnd] * nums[negativeEnd];
negativeEnd--;
}
}
while(activeBegin < nums.length) {
res[totalIndex++] = nums[activeBegin] * nums[activeBegin];
activeBegin++;
}
while(negativeEnd >= 0) {
res[totalIndex++] = nums[negativeEnd] * nums[negativeEnd];
negativeEnd--;
}
}
}
209.长度最小的子数组
leetcode题目链接:https://leetcode.cn/problems/minimum-size-subarray-sum
leetcode AC记录:
思路:双指针
target不满足条件时:说明需要更多的数字,窗口变大,right向右移动;
target满足条件时:说明已经满足,缩小窗口看是否继续满足,窗口变小,left向右移动;
代码如下:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
//处理异常条件
if(nums == null || nums.length <= 0) {
return 0;
}
int left = 0;
int right = 0;
//初始化sum
int sum = nums[0];
int currentSize = 1;
int res = Integer.MAX_VALUE;
while(left < nums.length && right < nums.length) {
if(sum >= target && res > currentSize) {
res = currentSize;
}
//操作
if(sum < target) {
right++;
currentSize++;
if(right < nums.length) {
sum += nums[right];
}
} else if(sum >= target){
sum -= nums[left];
left++;
currentSize--;
}
}
return res == Integer.MAX_VALUE ? 0 : res;
}
}
59.螺旋矩阵II
leetcode题目链接:https://leetcode.cn/problems/spiral-matrix-ii
leetcode AC记录:
思路:
1.移动按顺序分为4个方向:右、下、左、上;
2.向右移动后移动的次数减1,也就是接下来向下和向左均少一次移动,向下和向左移动的次数相同;
3.向下和向左移动后,移动的次数减1;
4.循环结束的条件为填充的数字小于等于n*n;
5.每个方向的移动均为一次循环,每次循环结束后需要将矩阵下标挪到下一次移动的开始位置。
代码如下:
class Solution {
public static int[][] generateMatrix(int n) {
int index = 1;
int[][] res = new int[n][];
//初始化结果集
for(int i = 0;i < n;i++) {
res[i] = new int[n];
}
int end = n * n;
int i = 0,j = 0;
int count = n;
while(index <= end) {
//向右:下标增加
for(int num = 0; num < count;num++){
res[i][j++] = index++;
}
j--;
i++;
//向下:下标增加,范围缩减
count--;
for(int num = 0; num < count;num++){
res[i++][j] = index++;
}
i--;
j--;
//向左:下标减小
for(int num = 0; num < count;num++){
res[i][j--] = index++;
}
j++;
i--;
//向上:下标减小,范围缩减
count--;
for(int num = 0; num < count;num++){
res[i--][j] = index++;
}
i++;
j++;
}
return res;
}
}