bonfy / algorithm-in-5-minutes

Algorithm in 5 minutes
0 stars 0 forks source link

2. Move Zeroes #2

Open bonfy opened 5 years ago

bonfy commented 5 years ago

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:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

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

bonfy commented 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
bonfy commented 5 years ago

解法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]
dVp007 commented 5 years ago
  1. JavaScript
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;
}