数组4、有序数组的平方

数组4、有序数组的平方

给你一个按 非递减顺序 排序的整数数组 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]

出处:https://leetcode-cn.com/problems/squares-of-a-sorted-array/

一、暴力解法:直接将数组进行平方,然后再用自带的排序方法进行排序即可

class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] rst = new int[nums.length];
        for(int i = 0; i<nums.length; i++){
            rst[i] = nums[i] * nums[i];
        }
        Arrays.sort(rst);
        return rst;
    }
}
二、双指针法

因为给定的数组是非递减的,只不过会有负数存在,平方之后可能会变大,所以最大的肯定是在两侧,依次往里递减,所以就从两边开始,两头进行比较,谁的平方大就存入,然后大的一方继续移动,与之前的小的进行比较,再存入大的,依次循环进行下去。

class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] rst = new int[nums.length];
        int k = rst.length-1;
        int i = 0;
        int j;
        for(j = nums.length - 1; i <= j;){
            if(nums[i] * nums[i] < nums[j] * nums[j]){
                rst[k--] = nums[j]*nums[j];
                j--;
            }else{
                rst[k--] = nums[i] * nums[i];
                i++;
            }
        }
        return rst;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

仲子_real

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

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

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

打赏作者

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

抵扣说明:

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

余额充值