【发布时间】:2014-12-05 22:16:42
【问题描述】:
给定一个正负数数组(没有零),我必须以正负数应该连续排列的方式排列它们。
正数和负数的个数可能不相等,即如果没有剩余的正数(或负数),则将所有剩余的负数(或正数)附加到数组的末尾。
顺序很重要,即如果输入数组是{2,-1,-3,-7,-8, 9, 5,-5,-7},那么输出数组应该是{2,-1, 9,-3, 5,-7,-8,-5,-7}。代码在 O(n) 中完成,无需使用另一个数组。
这是我在java中的解决方案,我再次测试了几个案例,它可以工作。但是,我不确定这是否在 O(n) 时间内运行。基本上,我先数正数和负数的个数。然后我有两个索引i = 0 和j =1。 j 总是领先一步 i。从那里我继续检查i 中的数字是否为正,j 是否为负,如果不是,i 将遍历数组,直到找到正确位置的下一个正/负并移动它到正确的位置。
非常感谢任何建议。谢谢!
//array of negative and positive, arrange them so that positive number follow by negative
// if no pos or neg left, the rest append to the array.
//should be O(n) no additional array
public static void alter(int[] a) {
int pos = 0;
int neg = 0;
int index = 0;
while (c < a.length) {
if (a[index] > 0) {
pos++;
} else neg++;
index++;
}
int i = 0;
int j = 1;
int temp = 0;
//run until no more positive number or negative number
while (pos > 0 && neg > 0) {
//
if (a[i] > 0) {
pos--;
if (a[j] < 0) {
i += 2;
j += 2;
neg--;
} else // a[j] > 0
{
while (a[j] > 0) {
j++;
}
//a[j] < 0
neg--;
//move that number to the appropriate place
while (j > i) {
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
j--;
} // end while
i += 2;
j += 2;
}
} else // a[i] < 0
{
while (a[i] < 0) {
i++;
}
//a[i] > 0
//move that number to the appropriate place
while (i > (j - 1)) {
temp = a[i];
a[i] = a[i - 1];
a[i - 1] = temp;
i--;
}
} //end else
}
}
【问题讨论】:
-
你必须只有一个数组吗?因为至少有两个会更好
-
是的,只允许一个数组