LeetCode-Squares of a Sorted Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/88524495

Description:
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

Example 1:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]

Example 2:

Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]

Note:

  • 1 <= A.length <= 10000
  • -10000 <= A[i] <= 10000
  • A is sorted in non-decreasing order.

题意:给定一个已排序的数组,要求将此数组中的每个元素求平方后重新排序;

解法一:最简单的做法就是先求数组中的所有元素重新赋值为其平方值,之后,再对这个数组进行排序;

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

解法二:因为给定的数组已经是有序的了,只是因为包含了正负数,所以求平方后可能数组前一部分的元素要大于后一部分的元素。但是,我们可以将此数组分为两个部分,第一个部分是包含所有的负数A,第二个部分包含所有的非负数B,我们同时从A的尾部和B的首部开始遍历,那么此时就相当于对两个有序的数组进行合并操作;
在这里插入图片描述

Java
class Solution {
    public int[] sortedSquares(int[] A) {
        int p1 = 0;
        int p2 = 0;
        while (p2 < A.length && A[p2] < 0) {
            p2++;
        }
        p1 = p2 - 1;
        int[] res = new int[A.length];
        int p = 0;
        while (p1 >= 0 && p2 < A.length) {
            if (A[p1] * A[p1] < A[p2] * A[p2]) {
                res[p++] = A[p1] * A[p1];
                p1--;
            } else {
                res[p++] = A[p2] * A[p2];
                p2++;
            }
        }
        while (p1 >= 0) {
            res[p++] = A[p1] * A[p1];
            p1--;
        }
        while (p2 < A.length) {
            res[p++] = A[p2] * A[p2];
            p2++;
        }
        
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/88524495