【LeetCode刷题-双指针】--977.有序数组的平方

977.有序数组的平方

【LeetCode刷题-双指针】--977.有序数组的平方_第1张图片

方法:双指针

由于数组是升序排序的,如果所有的数都是非负的,那么数组平方后,仍然保持升序,但数组中有负数,将每个数平方后,数组就会降序

需要找到数组中负数与非负数的分界线

使用两个指针分别指向0和n-1,比较两次指针对应的数,选择较大的值放入答案并移动指针

class Solution {
    public int[] sortedSquares(int[] nums) {
        int n = nums.length;
        int[] ans = new int[n];
        for(int i = 0,j = n - 1,pos = n-1;i<=j;){
            if(nums[i] * nums[i] > nums[j] * nums[j]){
                ans[pos] = nums[i] * nums[i];
                ++i;
            }else{
                ans[pos] = nums[j] * nums[j];
                --j;
            }
            --pos;
        }
        return ans;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法,数据结构)