中文:
给定一个整数数组A按递增顺序排序,返回每个数字的平方数组,也按有序递增顺序返回。
英文:
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.
解题思路:
这题比较简单了,
思路一:就是先算出每个元素的平方,然后再将每个元素平方后的数组,重新进行递增排序。递增排序最初考虑用快速排序算法,因为时间复杂度低。后面考虑都是int型数据,直接使用了Arrays.sort(A);进行排序。
package cn.leetcode.easy;
import java.util.Arrays;
/**
* 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.
*
* @author kimtian
*/
public class SquaresOfSortedArray {
/**
* 将数组每个元素进行平方,并按递增方式排序
*
* @param A 原数组
* @return 新数组
*/
public static int[] squaresOfSortedArray(int[] A) {
//将数组的每一个元素进行平方
for (int i = 0; i < A.length; i++) {
A[i] = A[i] * A[i];
}
/**
* 直接用自带的排序方法
*/
Arrays.sort(A);
return A;
}
/**
* 测试类
*
* @param args
*/
public static void main(String[] args) {
int[] a = {-4, -1, 0, 3, 10};
System.out.println(Arrays.toString(squaresOfSortedArray(a)));
}
}