看到题目,我优先想到暴力解法,没有想到双指针。 后来才看卡哥讲解才知道使用的是双指针。
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0,right = nums.length - 1;
int k = nums.length - 1;
int[] ans = new int[nums.length];
while(left <= right){
if(nums[left] * nums[left] > nums[right] * nums[right]){
ans[k --] = nums[left] * nums[left];
++left ;
}else{
ans[k --] = nums[right] * nums[right];
--right ;
}
}
return ans;
}
}
暴力解法: 首先定义一个最终的结果,定义一个sum用于计算子序列的数值之和,定义一个len作为子序列长度。然后使用两个for循环不断寻找符合条件的子序列。
双指针法:如果和暴力法都使用第一个for循环用来遍历开始位置则会超出时间限制,所以第一个for循环用来遍历终止位置。
在遍历终止位置的时候,每次遍历都将他们的和放入sum中,然后查看是否大于等于target,若大于则记录此时数组长度。然后就移动开始位置缩小子数组,看是否满足最小子数组,否则终止位置后移。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0;
int sum = 0;
int result = Integer.MAX_VALUE;
for(int right = 0;right < nums.length;right ++){
sum += nums[right];
while(sum >= target){
result = Math.min(result,right - left + 1);
sum -= nums[left ++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
一开始看到就想着怎么转,转不出来,磕磕碰碰。看过讲解以后,只要保证好边缘左闭右开或者左闭右闭的条件,即可迎刃而解。
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0,right = nums.length - 1;
int k = nums.length - 1;
int[] ans = new int[nums.length];
while(left <= right){
if(nums[left] * nums[left] > nums[right] * nums[right]){
ans[k --] = nums[left] * nums[left];
++left ;
}else{
ans[k --] = nums[right] * nums[right];
--right ;
}
}
return ans;
}
}
讲解文章:代码随想录