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:
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; } }
相关文章推荐
- LintCode "Interleaving Positive and Negative Numbers"
- lintcode-medium-Interleaving Positive and Negative Numbers
- Lintcode: Interleaving Positive and Negative Numbers
- LintCode Interleaving Positive and Negative Numbers
- [LintCode] Interleaving Positive and Negative Numbers
- 代码面试题:Interleaving Negative and Positive Numbers 正负交替
- Interleaving Positive and Negative Numbers
- Interleaving Positive and Negative Numbers
- Lintcode144 Interleaving Positive And Negative Numbers solution 题解
- Interleaving Positive and Negative Numbers
- Lintcode - Interleaving Positive and Negative Numbers
- lintcode:Interleaving Positive and Negative Numbers
- [leetcode]Interleaving Positive and Negative Numbers
- *[Lintcode]Interleaving Positive and Negative Numbers 交错正负数
- lintcode interleaving-string 交叉字符串
- Counting positive and negative number and computing the average of numbers
- lintcode 中等题:interleaving String 交叉字符串
- Codeforces Codeforces Round #432 (Div. 2 D ) Arpa and a list of numbers
- 【HDU5183】Negative and Positive (NP)
- Codeforces Round #235 (Div. 2) D. Roman and Numbers(状压dp)