力扣: 有序数组的平方

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落雨既然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值