Interleaving Positive and Negative Numbers
2017-10-18 19:56
369 查看
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
java
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.
java
public class Solution { /* * @param A: An integer array. * @return: nothing */ public void rerange(int[] A) { // write your code here if (A == null || A.length == 0) { return; } Arrays.sort(A); if (A.length % 2 == 0) { int left = 1; int right = A.length - 2; while (left <= right) { swap(A, left, right); left += 2; right -= 2; } } else if (A[(A.length - 1) / 2] < 0) { int left = 1; int right = A.length - 1; while (left <= right) { swap(A, left, right); left += 2; right -= 2; } } else { sort(A, 0, A.length - 1); int left = 1; int right = A.length - 1; while (left <= right) { swap(A, left, right); left += 2; right -= 2; } } } private void sort(int[] nums, int start, int end) { if (start > end) { return; } int left = start; int right = end; int pivot = nums[(start + end) / 2]; while (left <= right) { while (left <= right && nums[left] > pivot) { left++; } while (left <= right && nums[right] < pivot) { right--; } if (left <= right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; left++; right--; } } sort(nums, start, right); sort(nums, left, end); } private void swap(int[] nums, int left, int right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; } }
相关文章推荐
- LintCode Interleaving Positive and Negative Numbers
- Interleaving Positive and Negative Numbers
- [leetcode]Interleaving Positive and Negative Numbers
- *[Lintcode]Interleaving Positive and Negative Numbers 交错正负数
- 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.
- Interleaving Positive and Negative Numbers
- 代码面试题:Interleaving Negative and Positive Numbers 正负交替
- LintCode "Interleaving Positive and Negative Numbers"
- lintcode:Interleaving Positive and Negative Numbers
- Lintcode - Interleaving Positive and Negative Numbers
- Lintcode144 Interleaving Positive And Negative Numbers solution 题解
- Counting positive and negative number and computing the average of numbers
- Negative numbers and binary representation
- 1002 Positive and Negative
- Negative and Positive (NP) ( Hash 维护 )
- 【Best Coder 】 32 B Negative and Positive (NP)
- Rearrange an array of positive and negative integers