283. Move Zeroes

2018/04/09 leetcode 共 822 字,约 3 分钟

Title

the problem link

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.

题目意思就是把一个数组的非零元素移动到左边,零都移动到右边

Solution

第一个方法用另一个vector存储非零元素,再放和原vector零元素相同数量的0

第二个方法就是用指针的思想,in-place,像下面这样

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

网上还有一种,时间复杂度和空间复杂度类似,就是少个最后赋值为0


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

Search

    Table of Contents