LeetCode977. 有序数组的平方 Java 双指针法

题目描述

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

提示:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums 已按 非递减顺序 排序

进阶:

  • 请你设计时间复杂度为 O(n) 的算法解决本问题

AC代码以及注释

package leetcode_977_Squares_of_a_Sorted_Array;

/**
 * @Description: Given an integer array nums sorted in non-decreasing order,
 * return an array of the squares of each number sorted in non-decreasing order.
 * @Tips: Squaring each element and sorting the new array is very trivial,
 * could you find an O(n) solution using a different approach?
 */
class Solution {
    public static int[] sortedSquares(int[] nums) {

        int leastAbsIndex = 0;

        // 寻找nums中绝对值最小的值
        // 到了数值为0或者第一个正数就要停止,因为后面的绝对值一定比0或者第一个正数大
        while (nums[leastAbsIndex] <= 0 && leastAbsIndex != nums.length - 1 && nums[leastAbsIndex]
             * nums[leastAbsIndex + 1] > 0) {
            leastAbsIndex++;
        }

        // 如果leastAbsIndex所指向的位置的值不为0.则要判断左边和右边哪个绝对值比较小
        if (leastAbsIndex != nums.length - 1 && nums[leastAbsIndex] != 0) {
            leastAbsIndex = Math.abs(nums[leastAbsIndex]) > Math.abs(nums[leastAbsIndex + 1]) ?
                    leastAbsIndex + 1 : leastAbsIndex;
        }

        // 现在leastAbsIndex所指向的位置即为nums中绝对值最小的值
        int[] retNums = new int[nums.length];
        int temp = nums[leastAbsIndex];
        int index = 0;
        retNums[index++] = temp * temp;
        // 左右指针依次寻找当前状态下平方后值最小的值
        int leftIndex = leastAbsIndex - 1;
        int rightIndex = leastAbsIndex + 1;

        while (index < nums.length) {
            if (rightIndex >= nums.length || (leftIndex >= 0 && 
                    nums[leftIndex] * nums[leftIndex] < nums[rightIndex] * nums[rightIndex])) {
                retNums[index++] = nums[leftIndex] * nums[leftIndex];
                leftIndex--;
            } else {
                retNums[index++] = nums[rightIndex] * nums[rightIndex];
                rightIndex++;
            }
        }

        return retNums;
    }

    public static void main(String[] args) {
        int[] nums = sortedSquares(new int[]{-7, -3, 2, 3, 11});
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + " ");
        }
    }
}

时间以及空间复杂度 

  • 时间复杂度:O(n),其中 n 是数组长度。执行用时:1 ms,击败 100.00%使用 Java 的用户

  • 空间复杂度:O(1),内存消耗:42.68MB,击败 63.60%使用 Java 的用户

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一陸向北

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

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

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

打赏作者

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

抵扣说明:

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

余额充值