对于这个特殊问题,我试图删除排序数组中的冗余元素,并在数组末尾用0替换它们。例如,如果我有一个由int元素组成的数组
1,3,3,4,4,5,6,6,7
我的输出数组应该是
1,3,4,5,6,7,0,0,0
我第一次尝试这个问题是创建一个交换器,以便在删除元素后将所有0推送到列表的末尾,但它似乎不会将零推到列表的末尾。这是我的代码。
public void implode(int[] ary)
{
int swapper = -1;
int[] newARY = new int[ary.length];
int current = -1;
for (int i = 0; i < ary.length; i++)
{
if (current != ary[i])
{
newARY[i] = ary[i];
current = ary[i];
}
}
for (int i = 0; i < ary.length; i++)
{
if (ary[i] == 0)
{
if (ary[i + 1] != 0)
{
swapper = ary[i + 1];
ary[i] = swapper;
ary[i + 1] = 0;
}
}
}
ary = newARY;
for (int i = 0; i < newARY.length; i++)
{
System.out.print(newARY[i] + " ");
}
}
测试它的数组是,
int[] aryIn2 = {1, 1, 2, 3, 4, 4, 5, 6};
但是,在输出内爆阵列时,我收到了这个。
1 0 2 3 4 0 5 6
有什么我想念的吗?
提前致谢。
我观察到的代码有两个问题。
1)您的交换器逻辑正在执行与您之前修改过的阵列不同的阵列上的交换
2)您需要以冒泡排序的方式使用此逻辑,即循环内部循环
下面是您方法的工作修改示例代码。我只修改了第二个for-loop逻辑
public void implode(int[] ary) {
int swapper = -1;
int[] newARY = new int[ary.length];
int current = -1;
for (int i = 0; i < ary.length; i++) {
if (current != ary[i]) {
newARY[i] = ary[i];
current = ary[i];
}
}
for (int i = 0; i < newARY.length - 1; i++) {
if (newARY[i] == 0 && newARY[i + 1] != 0) {
for (int j = i; (j + 1) < newARY.length; j++) {
swapper = newARY[j + 1];
newARY[j] = swapper;
newARY[j + 1] = 0;
}
}
}
for (int i = 0; i < newARY.length; i++) {
System.out.print(newARY[i] + " ");
}
}
不是你的问题的答案,但使用(如果可能的话)java流可以缩短你的方式:
int[] arr = {1,3,3,4,4,5,6,6,7};
// distinct
List<Integer> list = Arrays.stream(arr).distinct().boxed().collect(Collectors.toList());
// pad with zero's
while(list.size() < arr.length) {
list.add(0);
}
// display
System.out.println(list.stream().map(String::valueOf).collect(Collectors.joining(",")));
将输出
1,3,4,5,6,7,0,0,0
在第一个循环中:
for (int i = 0; i < ary.length; i++) {
if (current != ary[i]) {
newARY[i] = ary[i];
current = ary[i];
}
}
你用qazxsw poi中的元素填充qazxsw poi,重复值变为0:
newARY
但是,在第二个循环中:
ary
你正在修改你原来的newARY: 1 0 2 3 4 0 5 6
阵列。所以newary没有更新。
但是,如果连续超过两个0,则尝试将0推送到数组末尾也会失败。并且它也容易受到ArrayOutOfBoundIndexException的攻击,因为你试图在 for (int i = 0; i < ary.length; i++)
{
if (ary[i] == 0)
{
if (ary[i + 1] != 0)
{
swapper = ary[i + 1];
ary[i] = swapper;
ary[i + 1] = 0;
}
}
}
上没有限制地阅读ary
将0推送到数组末尾的一种简单直接的方法是创建具有非0元素的新数组,并在以后填充0:
ary[i+1]
提示:使用上述策略,您可以简化代码。无需立即创建数组newARY。只需遍历原始数组,将唯一元素推送到结果数组,然后填充剩下0的任何插槽。