Problem: 977. 有序数组的平方
思路
首先这道题可以直接用暴力,for循环.加一个函数方法sort
但会提高实践复杂度,用双指针会优化
解题方法
因为非递减数组,在两边的平方要么是最大,要么是最小,一定是在两边,所以这时候可以用双指针,在数组两边定义两个指针,当左边的平方小于右边的平方,就往一个新数组放,放在最大索引处,然后左边++,同理,右边–.直到左边小于右边
复杂度
- 时间复杂度:
O ( n ) O(n) O(n)
Code
暴力
class Solution {
public int[] sortedSquares(int[] nums) {
int[] res = nums;
for(int i = 0 ; i < nums.length; i++){
res[i] *= nums[i];
}
Arrays.sort(res) ;//如果递减就 Arrays.sort(a, Collections.reverseOrder());
return res;
}
}
双指针
class Solution {
public int[] sortedSquares(int[] nums) {
int []res = new int[nums.length]; //递增存到新数组中
int k = nums.length-1; //新数组的索引
for(int l = 0, r = nums.length-1; l <= r; ){
if(nums[l]*nums[l] <= nums[r]*nums[r]) {
res[k--] = nums[r]*nums[r];
r --;
}
else{
res[k--] = nums[l]*nums[l];
l++;
}
}
return res;
}
}