LeetCode105|有序数组的平方

时间:2022-07-28
本文章向大家介绍LeetCode105|有序数组的平方,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

0x01,问题简述

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

0x02,示例

示例 1:

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

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

提示:

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

0x03,题解思路

计算+排序

0x04,题解程序


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortedSquaresTest {
    public static void main(String[] args) {
        int[] A = {-4, -1, 0, 3, 10};
        int[] sortedSquares = sortedSquares(A);
        for (int num : sortedSquares
        ) {
            System.out.print(num + "t");
        }
    }

    public static int[] sortedSquares(int[] A) {
        if (A == null || A.length == 0) {
            return new int[0];
        }
        List<Integer> list = new ArrayList<>(A.length);
        for (int num : A) {
            list.add(Math.abs(num) * Math.abs(num));
        }
        Collections.sort(list);
        int[] result = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }
        return result;
    }
}

0x05,题解程序图片版

0x06,总结一下

这道题也是属于正常思维的题了,一般也很容易做出来了,计算,排序,使用现有的方法进行操作和写逻辑题差不多,这也是本文的主要计算方式,这里替换了一下java8的用法,发现耗时还是很明显的,当然了,这里也可以使用双指针解决,这里给出示例程序


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortedSquaresTest {
    public static void main(String[] args) {
        int[] A = {-4, -1, 0, 3, 10};
        int[] sortedSquares = sortedSquares2(A);
        for (int num : sortedSquares
        ) {
            System.out.print(num + "t");
        }
    }

     

    public static int[] sortedSquares2(int[] A) {
        if (A == null || A.length == 0) {
            return new int[0];
        }
        int i = 0;
        int j = A.length - 1;
        int index = A.length - 1;
        int[] result = new int[A.length];
        while (index >= 0) {
            if (Math.abs(A[i]) < Math.abs(A[j])) {
                result[index--] = Math.abs(A[j]) * Math.abs(A[j]);
                j--;
            } else {
                result[index--] = Math.abs(A[i]) * Math.abs(A[i]);
                i++;
            }
        }
        return result;
    }
}

题解程序图片版