我需要将数组中所有的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;
}
}
谢谢!
我需要将数组中所有的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;
}
}
谢谢!
这是用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))
[1, 2, 0, 3, 4, 5, 0, 0, 0, 0]
。但这并不可行。 - Seenu Sa = [ 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]