Open bonfy opened 5 years ago
解法 1. 遍历
思路: 将每一个 非0 的数字 按顺序 与 第pos个数字进行交换
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
L = len(nums)
pos = 0
for i in range(L):
if nums[i] != 0:
nums[pos], nums[i] = nums[i], nums[pos]
pos += 1
解法2. Python 的语言特性
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
nums[:]=[x for x in nums if x!=0 ] +[i for i in nums if i==0]
function moveZero( a ) {
if( a instanceof Array ){
zeros = a.filter((count)=>count===0)
b = a.filter(zero => zero!==0);
a = b.concat(zeros);
return (b);
}
else
return 0;
}
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Note:
You must do this in-place without making a copy of the array. Minimize the total number of operations.
Leetcode: Move Zeroes - https://leetcode.com/problems/move-zeroes