给出一个含有正整数和负整数的数组,重新排列成一个正负数交错的数组。
样例
样例 1
输入 : [-1, -2, -3, 4, 5, 6]
输出 : [-1, 5, -2, 4, -3, 6]
解释 : 或者仍和满足条件的答案
挑战
完成题目,且不消耗额外的空间。
注意事项
不需要保持正整数或者负整数原来的顺序。
class Solution {
public:
/*
* @param A: An integer array.
* @return: nothing
*/
void rerange(vector<int> &A) {
// write your code here
int a=0,b;
for (int i = 0; i < A.size(); i++) {//统计正负数个数
/* code */
if(A[i]>0)a++;
}
b=A.size()-a;
if(b>=a)//负数多或正负一样多
{
for (int i = 0; i < A.size(); i++) {
/* code */
if(i%2==0&&A[i]>0)//双数下标为负数,单数下标为正数
{
int j=i+1;
while(A[j]>0) j++;
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
else if(i%2==0&&A[i]<0) continue;
else if(i%2&&A[i]<0)
{
int j=i+1;
while(A[j]<0) j++;
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
else continue;
}
}
else//正数多
{
for (int i = 0; i < A.size(); i++) {//双数下标为正数,单数下标为负数
if(i%2==0&&A[i]<0)
{
int j=i+1;
while(A[j]<0) j++;
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
else if(i%2==0&&A[i]<0) continue;
else if(i%2&&A[i]>0)
{
int j=i+1;
while(A[j]>0) j++;
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
else continue;
}
}
}
};