[LintCode] Interleaving Positive and Negative Numbers

本文介绍了一个算法,用于将包含正负整数的数组重新排列为交错顺序,即先出现一个负数,然后是正数,以此类推。通过在原地操作并避免使用额外内存来实现这一过程。

Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.

Example

Given [-1, -2, -3, 4, 5, 6], after re-range, it will be[-1, 5, -2, 4, -3, 6] or any other reasonable answer.

Note

You are not necessary to keep the original order of positive integers or negative integers.

Challenge

Do it in-place and without extra memory.

 

class Solution {
public:
    /**
     * @param A: An integer array.
     * @return: void
     */
     void rerange(vector<int> &A) {
       int n = A.size();
       if(n < 3) return;
       
       int posNum = 0, negNum = 0, posIdx = 0, negIdx = 1;
       for(size_t t = 0;t < n;++t){
           if(A[t] >= 0) ++posNum;
           else ++negNum;
       }
       
       if(negNum > posNum){
           negIdx = 0;
           posIdx = 1;
       }
       
       while(posIdx < n && negIdx < n){
           while(posIdx < n && A[posIdx] >= 0) posIdx += 2;
           while(negIdx < n && A[negIdx] < 0) negIdx += 2;
           if(posIdx < n && negIdx < n) swap(A[posIdx],A[negIdx]);
       }
   }
  
};

 

转载于:https://www.cnblogs.com/changchengxiao/p/4793731.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值