每日一题-Day24-有序数的平方


题目

给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序

解题思路

冒泡排序,先将数组的每一位数替换成该数的平方,利用冒泡排序对数组进行排序

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

双指针:该数组为递减数组,我们可以通过比较左右两端的数的大小,判断平方后的大小,将大数置于数组最后端

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array/