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();
        }
           
    };
  • 相关阅读:
    Flutter 路由管理
    SpringMVC 集成 MyBatis
    关于windows下安装mysql数据库出现中文乱码的问题
    md5.digest()与md5.hexdigest()之间的区别及转换
    MongoDB基础命令及操作
    redis相关操作&基本命令使用
    python中mysql主从同步配置的方法
    shell入门基础&常见命令及用法
    ORM总结
    多任务:进程、线程、协程总结及关系
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5119767.html
Copyright © 2011-2022 走看看