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();
        }
           
    };
  • 相关阅读:
    Java Json 数据下划线与驼峰格式进行相互转换
    Java反射常用示例
    ApplicationContextAware 快速获取bean
    Spring AOP自动代理创建者
    Spring依赖检查
    Bean作用域实例
    注入值到Spring bean属性
    用javaConfig 代替 xml 配置
    spring使用@Autowired装载
    Spring 概述
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5119767.html
Copyright © 2011-2022 走看看