zoukankan      html  css  js  c++  java
  • [LeetCode] 283. Move Zeroes 移动零

    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.

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    把一个数组里所有的0都移到后面,不能改变非零数的相对位置关系,而且不能拷贝额外的数组。

    要用替换法in-place,双指针来做,前面的指针指向处理过的最后一个非零数字, 后面一个指针向后扫,遇到非零数字,和前面指针所指数字交换位置,前面指针后移1位。

    或者不交换只把非零的数字换到前面,最后子统一把后面的全部变成0。

    Java: Time Complexity: O(n), Space Complexity: O(1)

    public class Solution {
        public void moveZeroes(int[] nums) {
            int index = 0;
            for (int i = 0; i < nums.length; ++i) {
                if (nums[i] != 0) {
                    nums[index++] = nums[i];
                }
            }
            for (int i = index; i < nums.length; ++i) {
                nums[i] = 0;
            }
        }
    }
    

    Python:

    class Solution(object):
        def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            pos = 0
            for i in xrange(len(nums)):
                if nums[i]:
                    nums[i], nums[pos] = nums[pos], nums[i]
                    pos += 1
    

    C++:

    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            int pos = 0;
            for (auto& num : nums) {
                if (num) {
                    swap(nums[pos++], num);
                }
            }
        }
    };
    

    类似题目:

    [LeetCode] 27. Remove Element

    All LeetCode Questions List 题目汇总  

  • 相关阅读:
    CF219D
    HDU 4259 Double Dealing 数学题
    HDU1599 find the mincost route 最小环
    HDU3592 World Exhibition 排队判断3种情况
    POJ3694 Network 加边查询剩余桥的个数
    Flex 如何获得Tree 拖动节点的起始位置
    wcf webconfig配置
    学JS面向对象 以及里面的继承
    sqlserver 几种查询耗时
    ubuntu更改文件夹属性
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8495822.html
Copyright © 2011-2022 走看看