leetcode hot100------283. 移动零

swap(nums, left, right);

Syntax:

public static void swap(List list, int i, int j)
Parameters: This method takes the following argument as a Parameter

list – The list in which to swap elements.
i – the index of one element to be swapped.
j – the index of the other element to be swapped.

java-solution

class Solution {
    public void moveZeroes(int[] nums) {
        int n = nums.length;
        int left = 0;
        int right = 0;
        while (right < n){
            //如果右指针不是0,左右指针互换,然后左指针+1,继续比较
            if(nums[right] != 0){
                //将nums中index为left和index为right的值互换
                swap(nums, left, right);
                //然后左指针往右移动,保持左指针左侧是非零
                left++;
            }
            //如果nums[right] == 0;则左指针不动,右指针向右
            //保证左指针到右指针之间是0
            right++;

        }

    }
    public void swap(int[] nums, int left, int right){
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
}

复杂度分析

时间复杂度:O(n),其中 n为序列长度。每个位置至多被遍历两次。

空间复杂度:O(1)。只需要常数的空间存放若干变量。

python solution

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        slow = 0
        for fast in range(len(nums)):
            if nums[fast] != 0 and nums[slow] == 0:
                nums[slow], nums[fast] = nums[fast], nums[slow]
            if nums[slow] != 0:
                slow += 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值