Interleaving Positive and Negative Numbers

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

Note: You are not necessary to keep the original order of positive integers or 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.

分析:

其实这题思路还是很简单的,先用partition方法把数组分成两队,左边的数是小于0的数,右边的数是大于0的数。

然后,我们需要把正数插入到负数里,但是之前我们要确认正数负数哪个更多。多的要放在第一个位置。

 1 class Solution {
 2     /**
 3      * @param A: An integer array.
 4      * @return: void
 5      * cnblogs.com/beiyeqingteng/
 6      */
 7     public void rerange(int[] A) {
 8         if (A == null || A.length <= 2) return;
 9         int pp = partition(A);  //positive number starting posisition
10         int np = 0; // negatie number starting position
11         if (A.length / 2 < pp) {
12             np++;
13         }
14         // put positive numbers into negative numbers
15         while (np <= A.length - 1 && pp <= A.length - 1) {
16             swap(A, np, pp);  
17             np = np + 2;
18             pp++;
19         } 
20    }
21 
22    // move negative to left
23    private int partition(int[] A) {
24        int p = 0;
25        for (int i = 0; i < A.length; i++) {
26            if (A[i] < 0) {
27                swap(A, i, p);
28                p++;
29            }
30        }
31        return p;
32    }
33    
34    private void swap(int[] A, int i, int j) {
35        int temp = A[i];
36        A[i] = A[j];
37        A[j] = temp;
38    }
39 }

转载请注明出处: cnblogs.com/beiyeqingteng/

posted @ 2016-06-30 05:12  北叶青藤  阅读(284)  评论(0编辑  收藏  举报