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 };
     
     
    一个比一个巧妙。
  • 相关阅读:
    SQL 查询两个时间段是否有交集的情况 三种写法
    c# 时间区间求并集
    uniapp 身份证识别 微信 百度 图片前端压缩 图片后端压缩
    Git命令大全
    构建android studio项目
    如何查tomcat进程和杀死进程
    mysql 备份 还原不了
    解决git extensions每次要输入用户名和密码
    JS string 转 Byte64[]
    Git cmd
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5678597.html
Copyright © 2011-2022 走看看