Leetcode

2019-02-07

2019-02-07  本文已影响0人  ruicore
LeetCode 283. Move Zeroes.jpg

LeetCode 283. Move Zeroes

Description

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]
Note:

You must do this in-place without making a copy of the array.
Minimize the total number of operations.

描述

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:

1.必须在原数组上操作,不能拷贝额外的数组。
2.尽量减少操作次数。

思路

# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-02-07 13:55:55
# @Last Modified by:   何睿
# @Last Modified time: 2019-02-07 14:07:46


class Solution:
    def moveZeroes(self, nums: 'List[int]') -> 'None':
        """
        Do not return anything, modify nums in-place instead.
        """
        # 获取第一个0的索引
        first = 0
        while first < len(nums):
            if nums[first] == 0:
                break
            first += 1
        # 如果0已经在最后一个位置或者没有0
        if first >= len(nums) - 1:
            return
        # 把第一个0和0后面的非零数替换
        # 并将first自增一次,指向下一个0
        for i in range(len(nums)):
            if nums[i] and i > first:
                nums[i], nums[first] = nums[first], nums[i]
                first += 1

源代码文件在这里.
©本文首发于何睿的博客,欢迎转载,转载需保留文章来源,作者信息和本声明.

上一篇 下一篇

猜你喜欢

热点阅读