Leetcode - 283 - move zeros

本文介绍了一种将数组中所有零元素移至末尾同时保持非零元素相对顺序的算法。提供了多种实现方案,包括使用双指针技术、快速排序思想等,并给出了C++、Java及Python的具体代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

Solutions:

(1) In the first loop, count the number of zeros.

      In the second loop, if not zero, move forward; if zero, move backward.

 

(2) Note that the number behind #count zeros, need to move forward #count times.

C++

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int zerosNum = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == 0) {
               zerosNum++; 
            } else {
                if (zerosNum != 0) {
                    int target = i - zerosNum;
                    nums[target] = nums[i];
                    nums[i] = 0; 
                } 
            }
        }
    }
};

 

(3) use index 'nonzero' to save the next to be saved nonzero place

C++

Two loops version:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int nonzero = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] != 0) {
                nums[nonzero++] = nums[i];  
            }
        }
        while (nonzero != nums.size()) {
            nums[nonzero++] = 0;
        }
    }
};

Java:

// Shift non-zero values as far forward as possible
// Fill remaining space with zeros

public void moveZeroes(int[] nums) {
    if (nums == null || nums.length == 0) return;        

    int insertPos = 0;
    for (int num: nums) {
        if (num != 0) nums[insertPos++] = num;
    }        

    while (insertPos < nums.length) {
        nums[insertPos++] = 0;
    }
}

https://leetcode.com/problems/move-zeroes/discuss/72011/Simple-O(N)-Java-Solution-Using-Insert-Index

 

C++

One loop version:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int nonzero = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] != 0) {
                nums[nonzero] = nums[i]; 
                if (i != nonzero) 
                    nums[i] = 0;
                nonzero += 1;
            }
        }
    }
};

(4)

参考了快速排序的思想,快速排序首先要确定一个待分割的元素做中间点x,然后把所有小于等于x的元素放到x的左边,大于x的元素放到其右边。
这里我们可以用0当做这个中间点,把不等于0(注意题目没说不能有负数)的放到中间点的左边,等于0的放到其右边。

C++

class Solution {
	public void moveZeroes(int[] nums) {
		if(nums==null) {
			return;
		}
		//两个指针i和j
		int j = 0;
		for(int i=0;i<nums.length;i++) {
			//当前元素!=0,就把其交换到左边,等于0的交换到右边
			if(nums[i]!=0) {
				int tmp = nums[i];
				nums[i] = nums[j];
				nums[j++] = tmp;
			}
		}
	}
}	

https://leetcode-cn.com/problems/move-zeroes/solution/dong-hua-yan-shi-283yi-dong-ling-by-wang_ni_ma/

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

https://leetcode.com/problems/move-zeroes/solution/

Python

class Solution(object):
	def moveZeroes(self, nums):
		"""
		:type nums: List[int]
		:rtype: None Do not return anything, modify nums in-place instead.
		"""
		if not nums:
			return 0
		# 两个指针i和j
		j = 0
		for i in xrange(len(nums)):
			# 当前元素!=0,就把其交换到左边,等于0的交换到右边
			if nums[i]:
				nums[j],nums[i] = nums[i],nums[j]
				j += 1

https://leetcode-cn.com/problems/move-zeroes/solution/dong-hua-yan-shi-283yi-dong-ling-by-wang_ni_ma/

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值