LeetCode977 有序数组的平方

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

找到中间0,然后双指针分别指向第一个正数和最后一个负数,每次比较两个数的绝对值,压入小者的平方。

需要注意在根据nums[pos]判断来增加pos的时候,一定要先判断pos是否在范围内。

 1 class Solution {
 2 public:
 3     vector<int> sortedSquares(vector<int>& nums) {
 4         int n=nums.size();
 5         int pos=0;
 6         for(int i=0;i<n;++i)
 7             if(nums[i]>=0){
 8                 pos=i;
 9                 break;
10             }
11         int l=pos-1;
12         vector<int> ans;
13         while(pos<n && nums[pos]==0){
14             ans.push_back(0);
15             ++pos;
16         }
17         int r=pos;
18         while(l>=0 && r<n){
19             if(abs(nums[l])<abs(nums[r])){
20                 ans.push_back(pow(nums[l],2));
21                 --l;
22             }
23             else{
24                 ans.push_back(pow(nums[r],2));
25                 ++r;
26             }
27         }
28         while(l>=0){
29             ans.push_back(pow(nums[l],2));
30             --l;
31         }
32         while(r<n){
33             ans.push_back(pow(nums[r],2));
34             ++r;
35         }
36         return ans;
37     }
38 };

猜你喜欢

转载自www.cnblogs.com/rookiez/p/13405519.html