977. 有序数组的平方
简单
给你一个按 非递减顺序 排序的整数数组 nums
,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
class Solution {
public int[] sortedSquares(int[] nums) {
for(int i =0; i<nums.length;++i){
nums[i]=nums[i]*nums[i];
}
Arrays.sort(nums);
return nums;
}
}
双指针参考:主要是时间复杂度O(n); 空间复杂度O(1)
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
for (int i = 0, j = n - 1, pos = n - 1; i <= j;) {
if (nums[i] * nums[i] > nums[j] * nums[j]) {
ans[pos] = nums[i] * nums[i];
++i;
} else {
ans[pos] = nums[j] * nums[j];
--j;
}
--pos;
}
return ans;
}
}
209. 长度最小的子数组
中等
给定一个含有 n
个正整数的数组和一个正整数 target
。
找出该数组中满足其和 ≥ target
的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr]
,并返回其长度。如果不存在符合条件的子数组,返回 0
。
暴力解法,超时!
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += nums[j];
if (sum >= target) {
ans = Math.min(ans, j - i + 1);
break;
}
}
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
}
参考双指针解法后:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int l=0;
int n=nums.length;
int ans=Integer.MAX_VALUE;
int sum=0;
for(int r=0;r<n;r++){
sum+=nums[r];
while(sum>=target){
ans=Math.min(ans,r-l+1);
sum-=nums[l++];
}
}
return ans==Integer.MAX_VALUE?0:ans;
}
}