leetcode 283 移动零

简介: leetcode 283 移动零

移动零

队列法

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        queue<int> myqueue;
        for(int i=0 ; i<nums.size() ;i++)
            if(nums[i] != 0) myqueue.push(nums[i]);
        for(int i=0 ; i<nums.size() ;i++)
        {
             if(myqueue.size()!=0)
            {
                nums[i] = myqueue.front();
                myqueue.pop();
            }else nums[i] = 0;
        }     
    }
};

双指针

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int left =0;
        for(int right = 0 ; right < nums.size() ;right++)
        {
            if(nums[right] != 0)
            {
                nums[left] = nums[right];
                left++;
            }
        }
        for(int i=left ; i<nums.size() ;i++)
            nums[i] = 0;
    }
};
相关文章
|
6天前
leetcode-472. 连接词
leetcode-472. 连接词
26 0
|
6天前
LeetCode
LeetCode
21 0
|
6天前
leetcode-475:供暖器
leetcode-475:供暖器
22 0
|
6天前
|
消息中间件 Kubernetes NoSQL
LeetCode 1359、1360
LeetCode 1359、1360
leetcode 827 最大人工岛
leetcode 827 最大人工岛
46 0
leetcode 827 最大人工岛
|
算法 Python
LeetCode 386. Lexicographical Numbers
给定一个整数 n, 返回从 1 到 n 的字典顺序。
59 0
LeetCode 386. Lexicographical Numbers
leetcode第37题
从上到下,从左到右遍历每个空位置。在第一个位置,随便填一个可以填的数字,再在第二个位置填一个可以填的数字,一直执行下去直到最后一个位置。期间如果出现没有数字可以填的话,就回退到上一个位置,换一下数字,再向后进行下去。
leetcode第37题
|
存储 算法
leetcode第49题
时间复杂度:两层 for 循环,再加上比较字符串,如果字符串最长为 K,总的时间复杂度就是 O(n²K)。 空间复杂度:O(NK),用来存储结果。 解法一算是比较通用的解法,不管字符串里边是大写字母,小写字母,数字,都可以用这个算法解决。这道题的话,题目告诉我们字符串中只有小写字母,针对这个限制,我们可以再用一些针对性强的算法。 下边的算法本质是,我们只要把一类的字符串用某一种方法唯一的映射到同一个位置就可以。
110 0
leetcode第49题
|
算法
leetcode第42题
也就是红色区域中的水, 数组是 height = [ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 ] 。 原则是高度小于 2,temp ++,高度大于等于 2,ans = ans + temp,temp = 0。 temp 初始化为 0 ,ans 此时等于 2。 height [ 0 ] 等于 0 < 2,不更新。 height [ 1 ] 等于 1 < 2,不更新。 height [ 2 ] 等于 0 < 2, 不更新。 height [ 3 ] 等于 2 >= 2, 开始更新 height [ 4 ] 等于 1 < 2,temp = temp + 1 = 1。 h
leetcode第42题
leetcode第21题
总 递归看起来,两个字,优雅!但是关于递归的时间复杂度,空间复杂度的求法,先留个坑吧。
leetcode第21题