Leetcode977(water problem) square of ordered array

Leetcode657 (water problem) square of ordered array

Title description:

Given an integer array A sorted in non-decreasing order, return a new array consisting of the square of each number, and it is required to also sort in non-decreasing order.

Example 1:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]

Example 2:

Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]

answer:

You can directly perform the square operation on the original vector, and then sort the vector.

AC code

class Solution {
    
    
public:
    vector<int> sortedSquares(vector<int>& A) {
    
    
        for(int i = 0; i < A.size(); i++)
            A[i] *= A[i];
        sort(A.begin(), A.end());
        return A;
    }
};

Welcome to reprint, indicate the source.

Question source: LeetCode
Link: https://leetcode-cn.com/problems/squares-of-a-sorted-array/

Guess you like

Origin blog.csdn.net/qq_36583373/article/details/109249745