将数组中的0移动到末尾

8

我需要将数组中所有的0移动到数组的末尾。

例如:[1, 10, 0, 5, 7] 应该变为 [1, 10, 5, 7, 0]。

我可以使用正向循环或反向循环。

不能创建新的数组。

这是我目前的代码:

for (int i = arr.length; i <= 0; --i) {
    if (arr[i] != 0) {
        arr[i] = arr.length - 1;
    }
}

谢谢!


你有任何限制吗? - dcow
1
沿着走,如果你发现一个零后面不跟着另一个零,那就交换它们。重复此过程直到没有更多的交换... - Boris the Spider
冒泡排序?... - dcow
@Gary McSperry,您编辑了这个问题。您的意思是您无法创建一个新的循环吗? - dcow
@DaidCowden 我的意思是我无法创建一个新数组,我的错。 - Nobody
显示剩余2条评论
22个回答

-1

这是用Python重新实现的:

Pythonic方式:

lst = [ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 ]

for i, val in enumerate(lst):
  if lst[i] == 0:
    lst.pop(i)
    lst.append(0)

print("{}".format(lst))

@dcow在Python中的实现:

lst = [ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 ]

i = 0                      # init the index value
for j in range(len(lst)):  # using the length of list as the range
  if lst[j] != 0:
    if i < j: 
      lst[i], lst[j] = lst[j], lst[i]  # swap the 2 elems.
  i += 1

 print("{}".format(lst))

Pythonic的解决方案是[1, 2, 0, 3, 4, 5, 0, 0, 0, 0]。但这并不可行。 - Seenu S

-1
a = [ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 ]

count = 0
for i in range(len(a)):
    if a[i] != 0:
        a[count], a[i] = a[i], a[count]
        count += 1 

print(a)
#op [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]

3
请勿仅仅发布代码,而应该包括一份解释,说明您的代码是如何解决问题的。这将极大地提高您的答案质量,并使其更有可能吸引赞同。 - Mark Rotteveel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接