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

Lintcode: Interleaving Positive and Negative Numbers

时间:2015-03-05 06:50:29      阅读:199      评论: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 or 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 legal answer.

Challenge
Do it in-place and without extra memory.

这道题没有给出正数、负数谁多谁少,所以需要先统计数量,数量多的要包着数量少的,然后数组尾部全是数量多的数

 1 class Solution {
 2     /**
 3      * @param A: An integer array.
 4      * @return an integer array
 5      */
 6     public int[] rerange(int[] A) {
 7         // write your code here
 8         int posNum = 0, negNum = 0;
 9         for (int elem : A) {
10             if (elem < 0) {
11                 negNum++;
12             }
13             else {
14                 posNum++;
15             }
16         }
17         int posInd = 1, negInd = 0;
18         if (posNum > negNum) {
19             negInd = 1;
20             posInd = 0;
21         }
22         while (posInd<A.length && negInd<A.length) {
23             while (posInd < A.length && A[posInd] > 0) {
24                 posInd += 2;
25             }
26             while (negInd < A.length && A[negInd] < 0) {
27                 negInd += 2;
28             }
29             if (posInd<A.length && negInd<A.length) {
30                 swap(A, posInd, negInd);
31                 posInd += 2;
32                 negInd += 2;
33             }
34         }
35         return A;
36    }
37    
38    public void swap(int[] A, int l, int r) {
39        int temp = A[l];
40        A[l] = A[r];
41        A[r] = temp;
42    }
43 }

 

Lintcode: Interleaving Positive and Negative Numbers

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/4314781.html

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