leetcode 026 —— Remove Duplicates from Sorted Array

来源:互联网 发布:工程项目优化管理ppt 编辑:程序博客网 时间:2024/06/16 17:34

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.


思路:题目要求去重复,如果真的去重复的话,代码如下 大约60ms

class Solution {public:int removeDuplicates(vector<int>& nums) {if (nums.empty()) return 0;if (nums.size() == 1) return 1;vector<int>::iterator  i = nums.begin(), j = i+1;while (j != nums.end()){if (*i== *j)j=nums.erase(j);else{i = j;j++;}}return nums.size();}};

如果不去重复,也能通过,代码如下

class Solution {public:    int removeDuplicates(int A[], int n) {        if(n==0) return 0;        int count=1;        for(int i=1;i<n;i++){            if(A[i]==A[i-1])                {                    continue;                }            else{                A[count]=A[i];                count++;            }        }        return count;   //    }};



0 0