1. 时间复杂度 = 空间复杂度 = O(n *
l
o
g
2
n
log_2{n}
log2?n)
- 最直接的想法就是先算出每个元素的平方和,然后排序,所以排序的效率就是这个算法的效率。那么目前综合性能比最好,实现也简单的就是快速排序算法,它的时间和空间复杂度为O(n *
l
o
g
2
n
log_2{n}
log2?n)
代码:时间复杂度O(n *
l
o
g
2
n
log_2{n}
log2?n).空间复杂度O(n *
l
o
g
2
n
log_2{n}
log2?n) |
---|
class Solution {
public int[] sortedSquares(int[] nums) {
for (int i = 0; i < nums.length; i++) {
nums[i] = (int)Math.pow(nums[i],2.0);
}
Arrays.sort(nums);
return nums;
}
public void quickSort(int arr[]){
quickSort(arr,0,arr.length-1);
}
public void quickSort(int arr[],int low,int high){
if(low<high){
int pivotPosition = quickSortPartition(arr, low, high);
quickSort(arr,low,pivotPosition-1);
quickSort(arr,pivotPosition+1,high);
}
}
public int quickSortPartition(int arr[],int low,int high){
int pivot = arr[low];
while (low<high){
while(low<high && arr[high]>=pivot) --high;
arr[low] = arr[high];
while(low<high && arr[low]<=pivot) ++low;
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
}
2. 时间复杂度O(n),空间复杂度O(1)
其实直接用排序算法,有些太奢侈了,而上面快速排序主要用双指针的思想。那么我们直接用双指针做这道题,是不是更好呢?
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int low = 0, high = n -1;
int position = n-1;
int[] answer = new int[n];
while(high >= low){
int leftPow = nums[low]*nums[low];
int rightPow = nums[high] * nums[high];
if(leftPow > rightPow) {answer[position] = leftPow; low++;}
else {answer[position] = rightPow; high--;}
position --;
}
return answer;
}
}