<LeetCode OJ> 26 / 80 Remove Duplicates from Sorted Array(I / II)

来源:互联网 发布:矩阵lu分解问题 编辑:程序博客网 时间:2024/06/06 14:15

26. Remove Duplicates from Sorted Array


Total Accepted: 104150 Total Submissions: 322188 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.




分析:

双指针问题,用len维护当前所有不重复的元素,用i遍历当前元素是否与相邻的元素相等!如果相等什么都不做,如果不相等则修改nums[len++]为当前这个元素。

class Solution {public: int removeDuplicates(vector<int> &nums) {    if(nums.size() < 2)         return nums.size();    int len = 1;    for(int i = 1; i < nums.size(); i++){        if(nums[i] != nums[i - 1])            nums[len++] = nums[i];    }    return len;    }};




80. Remove Duplicates from Sorted Array II

Total Accepted: 64365 Total Submissions: 202358 Difficulty: Medium

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3

It doesn't matter what you leave beyond the new length.


分析:

一个道理,双指针,一个指针始终指向当前安全的符合要求的序列,另一个遍历数组

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if(nums.size()<=2)            return nums.size();        int len=1,cnt=1;        for(int j=1;j<nums.size();j++)        {            if(nums[j]==nums[j-1])                cnt++;            else                cnt=1;            if(cnt < 3)                nums[len++] = nums[j];        }        return len;    }};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50499722

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

1 0