当前位置: 代码迷 >> 综合 >> Leetcode 977. Squares of a Sorted Array (C++)
  详细解决方案

Leetcode 977. Squares of a Sorted Array (C++)

热度:32   发布时间:2023-11-26 06:35:10.0

题目

在这里插入图片描述

解法:

class Solution {
    
public:vector<int> sortedSquares(vector<int>& A) {
    // get the dividing position of the negative and positive elementsint n = size(A);int div_pos=0;for (int i=0;i<n;i++){
    if (A[i]>=0){
    div_pos = i;break;}}// merge them using two pointervector<int> ans;int p1 = div_pos-1;int p2 = div_pos;while (p1>=0 && p2<n){
    if (A[p1]*A[p1]<A[p2]*A[p2]){
    ans.push_back(A[p1]*A[p1]);p1--;}else{
    ans.push_back(A[p2]*A[p2]);p2++;}}// add the left element from the arraywhile (p1>=0){
    ans.push_back(A[p1]*A[p1]);p1--;}while (p2<n){
    ans.push_back(A[p2]*A[p2]);p2++;}return ans;}
};
  相关解决方案