Array篇easy难度之平方后排序
2020-11-03 本文已影响0人
茉莉清可乐对奶茶i
本题关键字
two pointers
题目描述
https://leetcode.com/problems/squares-of-a-sorted-array/
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.
博主提交的代码
垃圾,一坨屎
public int[] sortedSquares(int[] A) {
int[] clone = A.clone();
for( int i = 0; i < clone.length;i++){
clone[i] = clone[i] * clone[i];
}
Arrays.sort(clone);
return clone;
}
别人优秀的代码
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/221922/Java-two-pointers-O(N)
class Solution {
public int[] sortedSquares(int[] A) {
int n = A.length;
int[] result = new int[n];
int i = 0, j = n - 1;
for (int p = n - 1; p >= 0; p--) {
if (Math.abs(A[i]) > Math.abs(A[j])) {
result[p] = A[i] * A[i];
i++;
} else {
result[p] = A[j] * A[j];
j--;
}
}
return result;
}
}