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

来源:互联网 发布:怎么样给数据库加锁 编辑:程序博客网 时间:2024/06/04 23:32

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;        }   }}


         



0 0