Leetcode - Happy Number
Leetcode - Max Consecutive Ones II

Leetcode - Move Zeroes

violet posted @ Apr 05, 2020 01:17:12 AM in 算法 with tags Algorithm Golang array , 161 阅读

https://leetcode.com/problems/move-zeroes/

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]

 

I've done such problems for ten thousand times.

func moveZeroes(nums []int) {
    left := 0
    right := left + 1
    for right < len(nums) {
        for left < len(nums) && nums[left] != 0 {
            left++
        }
        right = left+1
        for right < len(nums) && nums[right] == 0 {
            right++
        }
        if right >= len(nums) {
            break
        }
        nums[left] = nums[right]
        nums[right] = 0
        left++
    }
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter