Leetcode - Sort Transformed Array
Leetcode - Sort Array By Parity

Leetcode - Duplicate Zeros

violet posted @ Jul 14, 2020 04:23:12 AM in 算法 with tags Algorithm Golang array , 294 阅读

https://leetcode.com/problems/duplicate-zeros/

Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written.

Do the above modifications to the input array in place, do not return anything from your function.

 

Example 1:

Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

 

func duplicateZeros(arr []int)  {
    count := 0
    for _, n := range arr {
        if n == 0 {
            count++
        }
    }
    if count == 0 {
        return
    }
    
    for i := len(arr)-1; i >= 0; i-- {
        if arr[i] == 0 {
            count--
        }
        newIndex := i + count
        if newIndex >= len(arr) {
            continue
        }
        
        arr[newIndex] = arr[i]
        if arr[i] == 0 && newIndex+1 < len(arr) {
            arr[newIndex+1] = 0
        }
  
    }
}

登录 *


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