283 Move Zeroes

1 题目

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.

Example:

Input: [0,1,0,3,12]
Output: [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.

2 尝试解

2.1 分析

将所有0放到数组最后,其他数字相对顺序保持不变。可以从第一个数字开始,判断当前位置是否为0,如果是找到后续第一个非零数字,交换位置。

2.2 代码

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

3 标准解

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

猜你喜欢

转载自blog.csdn.net/weixin_39145266/article/details/89883576