双指针 leetcode 997
题目描述
题目理解
因为已经知道是双指针的题型,所以就直接往那个方向去想了。
直观思路(劣质):
一开始的想法是考虑负数,所以初始思路是找到与0最近的点然后左右向外比较扩散。但是这样由于0不在中心导致需要考虑left和right的OOR问题,目前编辑的版本当left==0后如果nums[left]<nums[right],仍然会更新left的赋值,最后预期结果与正确值不符,所以并不是一个好的思路。
class Solution {
public int[] sortedSquares(int[] nums) {
int len = nums.length , left = 0 ;
for(; left < len ; left ++){
if(nums[left+1]>=0){
break;
}
}
int right = left + 1;
int[] result = new int[len];
for (int i = 0 ; i < len ; i++) {
if (nums[right] <= -nums[left]){
result[i] = nums[right] * nums[right];
if(right + 1 < len){
right ++;
}
}else if (nums[right] > -nums[left]){
result[i] = nums[left] * nums[left];
if(left - 1 >=0){
left --;
}
}
}
return result;
}
}
优秀思路(优质):
虽然惯性思维是从小到大,但是其实可以逆序,因为不论是正数还是负数,目标数组的外侧的平方都是最大值,所以可以直接由大到小,倒序进行排列。
class Solution {
public int[] sortedSquares(int[] nums) {
int pos = nums.length - 1 , left = 0 , right = nums.length - 1;
int[] result = new int[pos + 1];
while( left <= right ){
if(nums[left] * nums[left] >= nums[right] * nums[right]){
result[pos] = nums[left] * nums[left] ;
left ++;
pos --;
}else{
result[pos] = nums[right] * nums[right] ;
right --;
pos --;
}
}
return result;
}
}
简便写法
class Solution {
public int[] sortedSquares(int[] nums) {
int start = 0 , end = nums.length -1 , pos = nums.length - 1 , len = nums.length;
int[] result = new int[len];
while( start <= end ){
result[pos--] = nums[start] * nums[start] > nums[end] * nums[end] ? nums[start] * nums[start ++] : nums[end] * nums[end --];
}
return result;
}
}
滑动窗口 leetcode209
题目描述
题目理解
滑动窗口的思想其实是很好理解的,但是需要注意的是条件的制约,这面主要需要理解的是,min_length我一开始设的是Integer.MAX_VALUE,但是有点太大了,可以设成数组长度len+1就可以,进而可以判断如果出现示例3的情况后强制将minlength = 0.
解题代码
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0 , right = 0 , len = nums.length , sum = 0 , minlength = nums.length + 1;
// minlength 这样设置可以有效解决不存在符合条件的数组时返回0的问题
while(right<len){
sum += nums[right];
while(sum >= target){
minlength = (right - left + 1) > minlength ? minlength:(right - left + 1);
sum -= nums[left ++];
}
right ++;
}
if (minlength == len + 1){ // 处理不存在符合条件的数组
minlength = 0 ;
}
return minlength;
}
}