暴力法:
使用Math.pow函数平方或者直接nums[i]*nums[i],Arrays.sort函数排序,时间复杂度为O(n+nlogn)
class Solution {
public int[] sortedSquares(int[] nums) {
for(int i = 0;i < nums.length;i++){
// nums[i] = nums[i]*nums[i];
nums[i] = (int)Math.pow(nums[i],2);
}
Arrays.sort(nums);
return nums;
}
}
双指针法:
因为nums为升序数组,所以两头的下标元素平方总有一个是要放置的数,使用双指针比较两头的元素,从大到小放置,哪个大放哪个,直到全放完,时间复杂带为O(n)
class Solution {
public int[] sortedSquares(int[] nums) {
int arr[] = new int[nums.length];
int start = 0;
int end = nums.length - 1;
int index = end;
while(start <= end){
int i = nums[start] * nums[start];
int j = nums[end] * nums[end];
if(i > j){
arr[index--] = i;
start++;
}else{
arr[index--] = j;
end--;
}
}
return arr;
}
}