leetcode#283. Move Zeroes

来源:互联网 发布:windows10查看mac表 编辑:程序博客网 时间:2024/06/14 06:56

Desciprtion

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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.

Code

class Solution:    def moveZeroes(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """        noneZero = []        for i in nums:            if i != 0:                noneZero.append(i)        i = 0        nlen = len(nums)        llen = len(noneZero)        while i < nlen:            if i < llen:                nums[i] = noneZero[i]            else:                nums[i] = 0            i += 1

算法本身没有问题,速度也还不错,快过80%,不过并不是最优解。它的空间复杂度是O(n)

Code2(官方solution)

void moveZeroes(vector<int>& nums) {    for (int lastNonZeroFoundAt = 0, cur = 0; cur < nums.size(); cur++) {        if (nums[cur] != 0) {            swap(nums[lastNonZeroFoundAt++], nums[cur]);        }    }}

这算是最优解了,交换了最少的次数,空间复杂度也只是O(1),时间复杂度都是O(n)

Conclusion

这题太简单了,没啥总结的。