有序数组的平方
给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。
示例 1:
输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]
思路+代码+注释:
public int[] sortedSquares(int[] A) {
/*
思路:使用优先级队列存储数据的平方,按照数据的平方进行建堆,时间复杂度为O(nlogn)
然后弹出所有堆顶元素,时间复杂度为O(nlogn),所以总的时间复杂度为O(nlogn)
*/
PriorityQueue<Integer> priorityQueue=new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
for (int i:A
) {
priorityQueue.add(i*i);
}
int k=0;
while (priorityQueue.size()>0)
{
A[k++]=priorityQueue.poll();
}
return A;
}