Leetcode - Best Time to Buy and Sell Stock II
Leetcode - Plus One

Leetcode - Move Zeroes

violet posted @ Mar 30, 2020 06:27:39 AM in 算法 with tags Algorithm Golang array , 240 阅读

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]

 

Just like this

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

登录 *


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