977. 有序数组的平方

给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
题目地址
详解地址

示例 1:

输入:nums = [-4,-1,0,3,10]
输出:[0,1,9,16,100]
解释:平方后,数组变为 [16,1,0,9,100]
排序后,数组变为 [0,1,9,16,100]
示例 2:

输入:nums = [-7,-3,2,3,11]
输出:[4,9,9,49,121]

暴解:

class Solution {
    public int[] sortedSquares(int[] nums) {
       for(int i=0;i<nums.length;i++){
           nums[i] *= nums[i];
       }
       Arrays.sort(nums);

        return nums;
    }
}

关注点:Arrays类加粗样式里提供了排序、二分查找类的静态方法,非常方便调用

空间换时间

class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] marks = new int[10001];
        for(int i=0;i<marks.length;i++){
            marks[i] = 0;
        }
        for(int i=0;i<nums.length;i++){
            marks[Math.abs(nums[i])]++;
        }
        int j=0;
        for(int i=0;i<marks.length&&j<nums.length;i++){
            while(marks[i] != 0){
                nums[j++] = i*i;
                marks[i]--;
            }

        }
        return nums;
    }
}

双指针法

class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] result = new int[nums.length];
        int head = 0,tail = nums.length - 1;
        int i = nums.length - 1;
        while(head<=tail){
            int rs1 = nums[head]*nums[head];
            int rs2 = nums[tail]*nums[tail];
            if(rs1<rs2){
                result[i--] = rs2;
                tail--;
            }else{
                result[i--] = rs1;
                head++;
            }
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值