有序数组的平方|双指针

有序数组的平方

有序数组的平方主要涉及两种算法,一种是直接暴力法,另一种是双指针

对应题目977. 有序数组的平方🎶

暴力法

定义一个新数组,再将原数组中的所有元素平方后存入新数组,最后利用快排进行排序,这里的时间复杂度取决于快排,所以是O(\(n\log_{2}{n}\)),空间复杂度为O(n)。给上java代码。

public int[] sortedSquares(int[] nums) {
        int[] arr = new int[nums.length];
        for(int i = 0;i < nums.length;i ++)
            arr[i] = nums[i] * nums[i];
        Arrays.sort(arr);
        return arr;
    }

双指针

同样定义一个新数组用来存储平方后的元素值。考虑到数组已经是由小到大是有序数组,因此最大值和最小值只可能出现在数组两端。所以定义两个指针,一前一后,分别指向原数组的起始位和末尾。再定义一个新数组的指针,指向新数组的末尾。循环遍历原数组,如果前指针所指元素值的绝对值大于后指针所指的,那么将此元素值平方存入新数组,并对指针进行操作。由于需要遍历,所以这里的时间复杂度为O(n),空间复杂度也为O(a)

// Define a function to get the absolute value of the element.
// It's used the bitwise operation to accelerate operation. 
int fastAbs(int n) {
    return (n^(n>>31)) - (n>>31);
}
vector<int> sortedSquares(vector<int>& nums) {
/* The k is the pointer of new array.It's is convenient to store
** data cause the new array store form rear to fornt.
*/
	int k = nums.size()-1;
    vector<int> results(nums.size());
    int i = 0,j = nums.size() - 1;
    while(i <= j){
        if(fastAbs(nums[i]) > fastAbs(nums[j])) {
            results[k] = nums[i] * nums[i];
            k--;
            i++;
        }else{
            results[k] = nums[j] * nums[j];
            k--;
            j--;
        }
    }
    return results;
}
posted on 2023-03-17 16:32  Coeleone  阅读(29)  评论(0)    收藏  举报