码迷,mamicode.com
首页 > 其他好文 > 详细

Interleaving Positive and Negative Numbers

时间:2016-06-30 06:28:32      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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 }
View Code

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

Interleaving Positive and Negative Numbers

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5628755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!