码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】1089. Duplicate Zeros

时间:2019-06-18 13:58:59      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:modified   rom   nal   list   func   not   else   inpu   output   

题目如下:

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]

Example 2:

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

 

Note:

  1. 1 <= arr.length <= 10000
  2. 0 <= arr[i] <= 9

解题思路:从头开始遍历arr,如果arr[i]等于0,在i+1位置插入0,索引移动到i+2;如果不为0,索引移动到i+1。

代码如下:

class Solution(object):
    def duplicateZeros(self, arr):
        """
        :type arr: List[int]
        :rtype: None Do not return anything, modify arr in-place instead.
        """
        length = len(arr)
        inx = 0
        while inx < length:
            if arr[inx] != 0:
                inx += 1
                continue
            else:
                arr.insert(inx,0)
                arr.pop(-1)
                inx += 2

 

【leetcode】1089. Duplicate Zeros

标签:modified   rom   nal   list   func   not   else   inpu   output   

原文地址:https://www.cnblogs.com/seyjs/p/11044681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!