【数组】3 种方法实现有序数组平方和【力扣977】

202 阅读1分钟

题目描述见链接 力扣第 977 题 力扣链接

拿到这道题,笨蛋的我首先想到了遍历数组给每个值赋予其本身的平方 再通过排序解决,但是本着对出题人的尊重 我没有这样做 而是琢磨了其他的方法解决他 这样更能达到练习提高的目的。

第一种:双指针法

定义一个长度与参数数组长度相等的数组

再定义一对双指针 分别位于数组的头和尾,来一场双向奔赴。

然后循环比较两个指针所在值的平方,将大的赋值给新数组的最后,然后维护好新数组的下标和指针就OK了。

int[] sortedSquares(int[] arr){
    int[] resultArr = new int[arr.length];
    int left = 0;
    int right = arr.length - 1;
    int leftSquares;
    int rightSquares;
    int index = arr.length - 1;
    while (left <= right){
        leftSquares = arr[left] * arr[left];
        rightSquares = arr[right] * arr[right];
        if(rightSquares > leftSquares){
            right--;
        }else{
            left++;
        }
        resultArr[index--] = Math.max(leftSquares, rightSquares);
    }
    return resultArr;
}

执行结果:

image.png


第二种:递归

只是将第一种方法变了个酱紫...脱了马甲还是ta

public int[] sortedSquares(int[] arr) {
   int[] resultArr = new int[arr.length];
   return sortedSquares(arr, 0, arr.length - 1, resultArr, resultArr.length - 1);
}

private int[] sortedSquares(int[] arr, int left, int right, int[] resultArr, int index){
    if(left > right){
        return resultArr;
    }
    int leftSquares = arr[left] * arr[left];
    int rightSquares = arr[right] * arr[right];
    resultArr[index] = Math.max(leftSquares, rightSquares);
    if(rightSquares > leftSquares){
        return sortedSquares(arr, left, right - 1, resultArr, index - 1);
    }else{
        return sortedSquares(arr, left + 1, right, resultArr, index - 1);
    }
}

执行结果:比上一种多耗时1ms ┭┮﹏┭┮ 但这不是最差的。

image.png

第三种:笨蛋法

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

执行结果:惊人的4ms ლ(ٱ٥ٱლ)

image.png

~~END~~