Leetcode C++《热题 Hot 100-14》283.移动零

喜你入骨 提交于 2020-02-02 01:19:22

Leetcode C++《热题 Hot 100-14》283.移动零

  1. 题目
    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:

必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/move-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  1. 思路
  • 是一个没做过的题目,参考冒泡swap的方法
    //1 0 0 3 12
    // 1 3 0 0 12
    // 1 3 12 0 0
  • 方案1(196ms,内存10MB):标记0的index-x,找到index-x之后的第一个不为0的数字进行交换, 时间复杂度n*n,比如最坏情况0 0 0 0 0 0 1
  • 方案2(8ms,内存10MB):时间复杂度为n,统计0的个数,直接把非0的移动到最终位置(index位置的最后位置是index-该位置前面0的个数)
  • 方案1的时间复杂度O(n)、空间复杂度O(1)
  1. 代码
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        /*int index_0 = -1;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == 0 && index_0 == -1) {
                index_0 = i;
            } 
            if (nums[i] != 0 && index_0 != -1) {
                swap(nums[i], nums[index_0]);
                index_0 = -1;
                i = index_0;
            }
        }*/
        int countZero = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == 0)
                countZero++;
            else {
                nums[i-countZero] = nums[i];
            }
        }
        for (int i = 0; i < countZero; i++) {
            nums[nums.size()-1-i] = 0;
        }
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!