您的位置:首页 > 其它

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