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

    26. Remove Duplicates from Sorted Array

    • Total Accepted: 142614
    • Total Submissions: 418062
    • Difficulty: Easy

    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.

     
     
     
    思路:重复的元素只保留1个,最后返回没有重复元素的vector.size()。
     
     
    代码:
    写法一:直接删除重复元素。
     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         int i=0,j;
     5         while(i<nums.size()){
     6             int temp=nums[i];
     7             while(i<nums.size()&&nums[i]==temp){
     8                 nums.erase(nums.begin()+i);
     9             }
    10             nums.insert(nums.begin()+i,temp);
    11             i++;
    12         }
    13         return nums.size();
    14     }
    15 };
    写法二:用id指针,只保留未重复的数。
     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         if(nums.size()==0){
     5             return 0;
     6         }
     7         int id=1,n=nums.size();
     8         for(int i = 1; i < n; ++i) 
     9             if(nums[i] != nums[i-1]) nums[id++] = nums[i];
    10         return id;
    11     }
    12 }; 
     
     
    写法三:
     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         int count=0,n=nums.size();
     5         for(int i=1; i<n; i++){
     6             if(nums[i] == nums[i-1]) count++;//count记录重复的元素个数
     7             else nums[i-count] = nums[i];
     8         }
     9         return n-count;
    10     }
    11 };
     
     
    一个比一个巧妙。
  • 相关阅读:
    将new Date()的时间转换为常用时间格式
    封装通用的jsonp方式
    javascript实现手机震动API代码
    webstorm 2016.3.2 破解代码(免费)
    淘宝镜像在npm中执行的代码
    jQuery lazyload 懒加载
    uniapp小程序获取时间戳转换时间例子
    微信小程序解析HTML标签
    微信小程序之tab切换效果
    巧用weui.gallery(),点击图片后预览图片
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5678597.html
Copyright © 2011-2022 走看看