0
点赞
收藏
分享

微信扫一扫

leetcode算法题解笔记--977. 有序数组的平方

悬灸人雪洋 2022-02-09 阅读 38

写题复盘:

一开始看到题目后首先看到了数字的平方就想到用Math.sqrt(),但是当提交后显示double->int会造成失真,就换用*法。先平方后再排序,选用的是快速排序(最坏情况为O(n^2),一般应该为O(nlogn)。

官方给的排序方法直接是Arrays.sort(),果然我还是太菜了😭

class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] sk=new int[100];
        int[] k=new int[nums.length];
        for(int i=0;i<nums.length;i++){
            k[i]=nums[i]*nums[i];
        }
        quickSort(k, 0, nums.length-1);
        return k;
    }
    public static void quickSort(int[] arr,int low,int high){
        int i,j,temp,t;
        if(low>high){
            return;
        }
        i=low;
        j=high;
        //temp就是基准位
        temp = arr[low];

        while (i<j) {
            //先看右边,依次往左递减,直到i=j就停止
            while (temp<=arr[j]&&i<j) {
                j--;
            }
            //再看左边,依次往右递增
            while (temp>=arr[i]&&i<j) {
                i++;
            }
            //如果满足条件则交换
            if (i<j) {
                t = arr[j];
                arr[j] = arr[i];
                arr[i] = t;
            }
        }
        //最后将基准为与i和j相等位置的数字交换
        arr[low] = arr[i];
        arr[i] = temp;
        //递归调用左半数组
        quickSort(arr, low, j-1);
        //递归调用右半数组
        quickSort(arr, j+1, high);
    }
}

 


官方题解:

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

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array/solution/you-xu-shu-zu-de-ping-fang-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

举报

相关推荐

0 条评论