代码随想录 977. 有序数组的平方

44 阅读1分钟

977. 有序数组的平方 - 力扣(LeetCode)

pow函数不能对负数进行平方:

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
     vector<int> result;
  for(auto ch:nums)
  {
      pow(ch,2);
      result.push_back(ch);
  }
  sort(result.begin(),result.end());
 return result;
    }
};

image.png

那就手动平方吧,x*=x;

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
     vector<int> result;
  for(auto ch:nums)
  {
      ch*=ch;
      result.push_back(ch);
  }
  sort(result.begin(),result.end());
 return result;
    }
};

image.png 时间复杂度就是快排的时间复杂度,nlong(n)