您的位置:首页 > 其它

LintCode-Interleaving Positive and Negative Numbers.

2014-12-27 00:52 429 查看
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.

Analysis:

We need figure how to address the cases that one kind of numbers is more than the other kind of numbers.

In LintCode, if postive numbers are more than negtive numbers, the array then start with positive numbers.

Solution:

class Solution {
/**
* @param A: An integer array.
* @return an integer array
*/
public int[] rerange(int[] A) {
if (A.length==0 || A.length==1) return A;

int posNum = 0;
for (int i : A) if (i>=0) posNum++;
int negP = (posNum>(A.length-posNum)) ? 1 : 0;
int posP = (posNum>(A.length-posNum)) ? 0 : 1;

    int p = A.length-1;
    while (negP<A.length && A[negP]<0) negP += 2;
    while (posP<A.length && A[posP]>=0) posP += 2;
    while (p>=posP || p>=negP){
    if (A[p]<0){
      if (negP>=A.length) p--;
     else {
      int temp = A[negP];
       A[negP] = A[p];
        A[p] = temp;
       negP += 2;
       }
     } else {
        if (posP >= A.length) p--;
      else {
         int temp = A[posP];
       A[posP] = A[p];
       A[p] = temp;
     posP += 2;
     }  
     }
    }

    return A;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: