leetcode-977-easy

Squares of a Sorted Array

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Example 1:

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
Example 2:

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

1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in non-decreasing order.
Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?

思路一:先平方后排序。还有一种思路,平方后,两端往中间是依次递减的有序数组,可以从两端往中间取值

    public static int[] sortedSquares(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }

        Arrays.sort(nums);

        return nums;
    }
    public static int[] sortedSquares(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }

        int[] result = nums.clone();

        int left = 0;
        int right = result.length - 1;
        int i = right;
        while (left <= right) {

            if (nums[left] < nums[right]) {
                result[i] = nums[right];
                right--;
            } else {
                result[i] = nums[left];
                left++;
            }

            i--;
        }

        return result;
    }
posted @ 2023-03-11 13:37  iyiluo  阅读(16)  评论(0)    收藏  举报