2019-01-29 Leetcode Day 4

Squares of a Sorted Array

1. 题目描述

一个排好序的数组,把这个数组的每个元素取平方后排序,返回排好序的数组。

2. 解法

2.1 构造数组,利用内联函数排序

class Solution {
    public int[] sortedSquares(int[] A) {
        int N = A.length;
        int[] ans = new int[N];
        for (int i = 0; i < N; ++i)
            ans[i] = A[i] * A[i];

        Arrays.sort(ans);
        return ans;
    }
}

2.2 利用排序特性,正数负数分别比较,降低时间复杂度。

class Solution {
    public int[] sortedSquares(int[] A) {
        int N = A.length;
        int j = 0;
        while (j < N && A[j] < 0)
            j++;
        int i = j-1;

        int[] ans = new int[N];
        int t = 0;

        while (i >= 0 && j < N) {
            if (A[i] * A[i] < A[j] * A[j]) {
                ans[t++] = A[i] * A[i];
                i--;
            } else {
                ans[t++] = A[j] * A[j];
                j++;
            }
        }

        while (i >= 0) {
            ans[t++] = A[i] * A[i];
            i--;
        }
        while (j < N) {
            ans[t++] = A[j] * A[j];
            j++;
        }

        return ans;
    }
}

最后顺便练习了一下快速排序,但是实际效果并没有这么好:

class Solution {
    public int[] sortedSquares(int[] A) {
        for (int i=0;i

你可能感兴趣的:(2019-01-29 Leetcode Day 4)