LintCode Interleaving Positive and Negative Numbers
2017-02-16 16:42
447 查看
description:
Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.
Notice
You are not necessary to keep the original order of positive integers or negative integers.
Have you met this question in a real interview? Yes
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.
同样是使用two pointers的算法进行处理。但是此时的two pointer的方法是使用的同向的双指针进行的
Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.
Notice
You are not necessary to keep the original order of positive integers or negative integers.
Have you met this question in a real interview? Yes
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.
同样是使用two pointers的算法进行处理。但是此时的two pointer的方法是使用的同向的双指针进行的
class Solution { /** * @param A: An integer array. * @return: void */ public void rerange(int[] A) { // write your code here if (A == null || A.length == 0 || A.length == 1) { return; } int pos = 0; int neg = 0; for (int i = 0; i < A.length; i++) { if (A[i] < 0) { neg++; } else { pos++; } } int posind = 1; int negind = 0; if (neg < pos) { posind = 0; negind = 1; } while (posind < A.length && negind < A.length) { if (A[posind] > 0) { posind += 2; } if (A[negind] < 0) { negind += 2; } if (posind < A.length && negind < A.length) { swap(A, posind, negind); } } } private void swap(int[] A, int left, int right) { int temp = A[left]; A[left] = A[right]; A[right] = temp; } }
相关文章推荐
- Lintcode: Interleaving Positive and Negative Numbers
- 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
- Interleaving Positive and Negative Numbers
- 代码面试题:Interleaving Negative and Positive 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 交叉字符串
- HDU 5183 Negative and Positive (NP) 前缀和+哈希
- Lintcode - Serialization and Deserialization Of Binary Tree
- CLR Inside Out: Best Practices for Managed and Native Code Interoperability (托管/非托管代码互通性最佳实践)