2021.09.17 - 048.有序数组的平方

258 篇文章 0 订阅

1. 题目

在这里插入图片描述

2. 思路

(1) 双指针法

  • 首先找到最小元素的下标,然后令left向左遍历,right向右遍历,依次向新数组中加入较小的值。
  • 若一个指针先到达边界,则将另一个指针之后的元素直接加入新数组即可。

(2) 双指针法优化

  • 与(1)的思想基本相同,(1)是从内向外依次找到较小值,也可以从外向内依次找到较大值,然后倒序加入新数组,这样省去了找最小元素下标的时间。

3. 代码

public class Test {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] ints = solution.sortedSquares(new int[]{-4, -1, 0, 3, 10});
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }
}

class Solution {
    public int[] sortedSquares(int[] nums) {
        int minIndex = 0;
        nums[0] = nums[0] * nums[0];
        for (int i = 1; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
            if (nums[i] < nums[i - 1]) {
                minIndex = i;
            }
        }
        int[] res = new int[nums.length];
        res[0] = nums[minIndex];
        int index = 1;
        int left = minIndex - 1;
        int right = minIndex + 1;
        while (left >= 0 && right <= nums.length - 1) {
            if (nums[left] < nums[right]) {
                res[index++] = nums[left--];
            } else {
                res[index++] = nums[right++];
            }
        }
        if (right == nums.length) {
            while (index < nums.length) {
                res[index++] = nums[left--];
            }
        } else {
            while (index < nums.length) {
                res[index++] = nums[right++];
            }
        }
        return res;
    }
}

class Solution1 {
    public int[] sortedSquares(int[] nums) {
        int[] res = new int[nums.length];
        int left = 0;
        int right = nums.length - 1;
        int index = nums.length - 1;
        int leftValue;
        int rightValue;
        while (index >= 0) {
            leftValue = nums[left] * nums[left];
            rightValue = nums[right] * nums[right];
            if (leftValue > rightValue) {
                res[index--] = leftValue;
                left++;
            } else {
                res[index--] = rightValue;
                right--;
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值