★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-mjgcplnx-ma.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a fixed length array arr
of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.git
Note that elements beyond the length of the original array are not written.github
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]
Example 2:函數
Input: [1,2,3] Output: null Explanation: After calling your function, the input array is modified to: [1,2,3]
Note:spa
1 <= arr.length <= 10000
0 <= arr[i] <= 9
給你一個長度固定的整數數組 arr
,請你將該數組中出現的每一個零都複寫一遍,並將其他的元素向右平移。code
注意:請不要在超過該數組長度的位置寫入元素。htm
要求:請對輸入的數組 就地 進行上述修改,不要從函數返回任何東西。 blog
示例 1:
輸入:[1,0,2,3,0,4,5,0] 輸出:null 解釋:調用函數後,輸入的數組將被修改成:[1,0,0,2,3,0,0,4]
示例 2:
輸入:[1,2,3] 輸出:null 解釋:調用函數後,輸入的數組將被修改成:[1,2,3]
提示:
1 <= arr.length <= 10000
0 <= arr[i] <= 9
1 class Solution { 2 func duplicateZeros(_ arr: inout [Int]) { 3 var n:Int = arr.count 4 var a:[Int] = arr 5 var p:Int = 0 6 for i in 0..<n 7 { 8 if a[i] == 0 9 { 10 if p < n 11 { 12 arr[p] = 0 13 p += 1 14 } 15 if p < n 16 { 17 arr[p] = 0 18 p += 1 19 } 20 } 21 else 22 { 23 if p < n 24 { 25 arr[p] = a[i] 26 p += 1 27 } 28 } 29 } 30 31 } 32 }
1 class Solution { 2 func duplicateZeros(_ arr: inout [Int]) { 3 let c = arr.count 4 if c <= 1 { return } 5 6 var i = 0 7 while i < c { 8 if arr[i] == 0 { 9 arr.insert(0, at: i) 10 i += 2 11 } else { 12 i += 1 13 } 14 } 15 while arr.count > c { 16 _ = arr.popLast() 17 } 18 } 19 }
48ms
1 class Solution { 2 func duplicateZeros(_ arr: inout [Int]) { 3 var count = 0 4 for (index, value) in arr.enumerated() { 5 if value == 0 { 6 count += 1 7 } 8 } 9 var index = arr.count - 1 10 while index >= 0 { 11 let value = arr[index] 12 if index + count < arr.count { 13 arr[index + count] = value 14 } 15 if value == 0 { 16 count -= 1 17 if index + count < arr.count { 18 arr[index + count] = 0 19 } 20 } 21 index -= 1 22 } 23 } 24 }