zoukankan      html  css  js  c++  java
  • Remove Duplicates from Sorted Array

    Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

    Do not allocate extra space for another array, you must do this in place with constant memory.

    For example,
    Given input array nums = [1,1,2],

    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

    Subscribe to see which companies asked this question

    Show Tags
     多个方法,其中带erase的耗时时间比较长
    class Solution {
    public:
        /*
        * 遍历vector如果第一个数字和前面相邻相等,就去掉第该数字
        *
        */
        int _removeDuplicates(vector<int>& nums) {
            int len = 0;
            int value = INT_MIN;
            int i = 0;
            for (i=0; i< nums.size(); i++) {
                if (nums[i] != value) {
                    value = nums[i];
                    len++;
                } else {
                    nums.erase(nums.begin() + i);
                    i--;
                }
            }
            return len;
        }
        
        int __removeDuplicates(vector<int>& nums) {
               int len = 0;
               int value = INT_MAX;
               nums.push_back(INT_MIN);
               vector<int>::iterator iter = nums.begin();
               while ((*iter) != INT_MIN) {
                   if ((*iter) != value) {
                       value = (*iter);
                       len++;
                       iter++;
                   } else {
                       nums.erase(iter);
                   }
               }
               return len;
           }
         //新弄一个vector,将不重复的放入该vector中
        int removeDuplicates(vector<int>& nums) {
            vector<int> res;
            int value = INT_MAX;
            nums.push_back(INT_MIN);
            vector<int>::iterator iter = nums.begin();
            while ((*iter) != INT_MIN) {
                if ((*iter) != value) {
                    value = (*iter);
                    res.push_back(value);
                } 
                iter++;  
            }
            nums = res;
            return res.size();
        }
           
    };
  • 相关阅读:
    暑假D16 T3 密道(数位DP? 打表找规律)
    暑假D16 T2 无聊 (深搜)
    暑假D14 T3 cruise(SDOI2015 寻宝游戏)(虚树+set)
    Django url
    http协议
    host文件以及host的作用
    用socket写一个简单的服务器
    python中*args **kwargs
    javascript 判断对像是否相等
    html input标签详解
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5119767.html
Copyright © 2011-2022 走看看