LC977有序数组的平方
分析:二刷但是思路仍然没有想通,主要问题出在对于”有序数组“的理解上,有序数组是两头高中间低的数组,因此最终的结果数组的最大值一定出现在两端,这么想思路就有了,结合双指针可以解决。
具体过程:两个双指针指向所给数组的开头(0)和结尾(nums.length - 1),一个指针指向结果数组的末尾,用于填充有序数组平方的最大值,最终返回结果数组。
代码:
public int[] sortedSquares(int[] nums) {
int[] result = new int[nums.length];
int k = nums.length - 1;
//最大元素一定在两边
for(int i = 0, j = nums.length - 1; i <= j;){
if(nums[i] * nums[i] < nums[j] * nums[j]){
result[k] = nums[j] * nums[j];
k--;
j--;
}else{
result[k] = nums[i] * nums[i];
k--;
i++;
}
}
return result;
}
LC209长度最小的子数组
分析:经典的双指针类型的题目,start和end指针,end指针向前移动至数组末尾,移动一步统计[start, end]区间中的sum值,当sum >= target时,需要进行更新和记录操作,记录此时的区间长度,同时start向前移动,sum重新累加到下一次大于等于target的时候。类似于用双指针模拟滑动窗口。
代码:
public int minSubArrayLen(int target, int[] nums) {
int result = Integer.MAX_VALUE;
int start = 0;
int sum = 0;
for(int end = 0; end < nums.length; end++){
sum += nums[end];
while(sum >= target){
int len = end - start + 1;
result = Math.min(result, len);
sum -= nums[start];
start++;
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
LC59螺旋数组Ⅱ
分析:遍历每条边时,遵循的循环不变量是左闭右开,定义两个起始位置坐标startx,starty,一个修正一圈的坐标值offset, 同时由于从1到n*n的螺旋数组,需要转的圈数是n/2,当n/2是奇数时,填满中心位置result[n/2][n/2]即可。
每一圈遍历时,遵循左闭右开原则,一圈一圈向内填数,每一圈遍历完后,更新起始位置startx, starty, 修正值offset和循环次数loop即可。
代码:
public int[][] generateMatrix(int n) {
int[][]result = new int[n][n];
int startx = 0, starty = 0;
int offset = 1;
int loop = 1;
int count = 0;
int i,j;
while(loop <= n/2){
for(j = starty;j < n - offset;j++){
count++;
result[startx][j] = count;
}
for(i = startx;i < n - offset;i++){
count++;
result[i][j] = count;
}
for(;j > starty;j--){
count++;
result[i][j] = count;
}
for(;i > startx;i--){
count++;
result[i][j] = count;
}
startx++;
starty++;
offset++;
loop++;
}
if(n%2 == 1){
result[n/2][n/2] = n*n;
}
return result;
}