其他分享
首页 > 其他分享> > leetcode977(双指针)

leetcode977(双指针)

作者:互联网

mycode:
class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
           int n = 100000;
            int x = 0;
            for(int i=0;i<nums.size();i++){    
                if(abs(nums[i])<n){
                    n = abs(nums[i]);
                    x = i;
                }
                nums[i]*=nums[i];
            }
            vector<int> backup = nums;
                int cnt=0;
                nums[0]=nums[x];
                int i=x-1;
                int j=x+1;
            while(cnt<nums.size()-1){
                if(i<0) nums[++cnt]=backup[j++];
                else if(j>nums.size()-1) nums[++cnt] = backup[i--];
                else{
                
                if(backup[i]>backup[j]){
                    nums[++cnt] = backup[j];
                    j++;
                }
                else {
                    nums[++cnt] = backup[i];
                    i--;
                }
        }
                    
            }
            return nums;
    }
};

 

标签:cnt,vector,nums,int,++,leetcode977,backup,指针
来源: https://www.cnblogs.com/z218/p/16663820.html