力扣977题(有序数组的平方)

977、有序数组的平方

基本思想:

双指针法

左右指针

具体实现:

1、数组是有序的,但是负数平方后可能会变大

2、数组平方后的最大值在数组的最右端或者最左端

3、left指向数组起始位置,right指向数组终止位置

4、定义一个和原始数组一样大的新数组result

5、定义一个指针指向result的终止位置

6、如果nums[left]的平方小于nums[right]的平方,result[index--] = nums[right]的平方

7、right往左移,left不动

 

 

代码:

class Solution {
    public int[] sortedSquares(int[] nums) {
        int right = nums.length -1;
        int left = 0;
        int[] result = new int[nums.length];
        int index = result.length - 1;
        while (left <= right) {
            if (nums[left] * nums[left] > nums[right] * nums[right]){
                result[index--] = nums[left] * nums[left];
                left++;
            }
            else{
                result[index--] = nums[right] * nums[right];
                right--;
            }
        }
        return result;
    }
}

 

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

 

posted @ 2021-10-09 16:25  最近饭吃的很多  阅读(31)  评论(0编辑  收藏  举报