LeetCode 977. Squares of a Sorted Array

977.Squares of a Sorted Array(有序数组的平方)

链接

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

题目

给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

示例 1:

  输入:[-4,-1,0,3,10]
  输出:[0,1,9,16,100]

示例 2:

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

提示:

  1. 1 <= A.length <= 10000
  2. -10000 <= A[i] <= 10000
  3. A 已按非递减顺序排序。

思路

非递减顺序,再加上存在负数,可以通过在两端比较,比较两个数的平方,平方较大者,放到新数组的靠后位置。

代码

    public static int[] sortedSquares(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        int tag = nums.length - 1;
        int [] ans = new int[nums.length];
        while (left <= right) {
            int i = nums[left] * nums[left];
            int j = nums[right] * nums[right];
            if (i <= j) {
                ans[tag--] = j;
            } else {
                ans[tag--] = i;
                left++;
            }
        }
        return ans;
    }
posted @ 2019-06-03 10:32  cheng102e  阅读(150)  评论(0编辑  收藏  举报