给出一个含有正整数和负整数的数组,重新排列成一个正负数交错的数组。
给出数组[-1, -2, -3, 4, 5, 6]
,重新排序之后,变成[-1,
5, -2, 4, -3, 6]
或者其他任何满足要求的答案
不需要保持正整数或者负整数原来的顺序。
原地完成,没有额外的空间
class Solution {
public:
/**
* @param A: An integer array.
* @return: void
*/
void rerange(vector<int> &A) {
// write your code here
int n=A.size();
if(n<=2) return;
int low=0,high=n-1;
while(low<high){
while(low<high&&A[low]<0){low++;}
while(low<high&&A[high]>0){high--;}
if(low<high) swap(A[low],A[high]);
}
int count1=0,count2=0;
for(int i=0;i<n;i++){
if(A[i]<0) count1++;
else count2++;
}
int left=0,right=n-1;
if(count1>count2) left++;
else if(count1<count2) right--;
while(left<right){
swap(A[left],A[right]);
left+=2;
right-=2;
}
}
};