*[Lintcode]Interleaving Positive and Negative Numbers 交错正负数

本文介绍了一种不使用额外空间对包含正负整数的数组进行重排的方法,使其成为正负整数交错排列的形式。通过排序及双指针技术实现,确保了复杂度为O(n)。

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

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.

分析:题目要求不使用额外空间。所以考虑双指针。先排序并确定占多数的是负数还是整数,根据不同情况,确定指针起始位置。复杂度O(n)


例:-1 -2 -3 4 5 start = 1 end = 4       -1 -2 3 4 5 start = 0, end = 3        -1 -2 3 4 start = 0, end = 3 确保占多数的一组先移动一位。


class Solution {
    /**
     * @param A: An integer array.
     * @return: void
     */
    public void rerange(int[] A) {
        if(A.length <= 1) return;
        
        Arrays.sort(A);
        
        int start = 0, end = A.length - 1;
        if(A.length % 2 != 0 && A[A.length / 2] > 0) end = A.length - 2;
        if(A.length % 2 != 0 && A[A.length / 2] < 0) start = 1;
        
        while(start < end) {
            int tmp = A[start];
            A[start] = A[end];
            A[end] = tmp;
            start += 2;
            end -= 2;
        }
   }
}


         



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值