Please enable Javascript to view the contents

26. Remove Duplicates from Sorted Array 消去重复数

 ·   ·  ☕ 1 分钟 · 👀... 阅读

    题目

    难度:

    传送门:

    思路

    一开始没有仔细看题,以为只要求出消去重复数之后数组的长度就行了,没看到还要求最后的数组。于是用了很笨的方法。

    后来看了解答,双指针,很快就出来了。

    不过,但是还是卡了一下,因为没有判断数组为空的情况。以后得引起注意啊。

    代码

    时间复杂度:O(n)

    空间复杂度:O(1)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            if (nums.size() == 0) {
                return 0;
            }
            
            int i = 0;
            for (int j = 1; j < nums.size(); j++) {
                if (nums[i] != nums[j]) {
                    i++;
                    nums[i] = nums[j];
                }
            }
            return i + 1;
        }
    };
    

    结果

    Runtime: 24 ms, faster than 59.96% of C++ online submissions….

    Memory Usage: 9.9 MB, less than 83.75% of C++ online submissions….

    可能优化的点

    运行时间还是太慢,但一时找不到优化的点。


    YoungWilliam
    作者
    YoungWilliam
    Stay young and optimatic.

    目录