Lintcode - Interleaving Positive and Negative Numbers

本文介绍了一种算法,用于将包含正负整数的数组重新排列为交替的正负序列,同时在原地操作且不使用额外内存。通过遍历数组并根据元素的正负性定位插入位置,最终实现数组的交替重组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

Do it in-place and without extra memory

    public int[] rerange(int[] A) {
        int posNum = 0, negNum = 0;
        for (int i = 0; i < A.length; i++) {
            if (A[i] > 0) {
                posNum++;
            } else {
                negNum++;
            }
        }
        int posInd = 1, negInd = 0;
        if (posNum > negNum) {
            posInd = 0;
            negInd = 1;
        }
        
        while (negInd < A.length && posInd < A.length) {
            while (negInd < A.length && A[negInd] < 0) {
                negInd += 2;
            }
            while (posInd < A.length && A[posInd] > 0) {
                posInd += 2;
            }
            if (posInd < A.length && negInd < A.length) {
                swap(posInd, negInd, A);
                posInd += 2;
                negInd += 2;
            }
        }
        return A;
   }
   
   void swap(int left, int right, int[] A) {
       int tmp = A[left];
       A[left] = A[right];
       A[right] = tmp;
   }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值