【leetcode】26. Remove Duplicates from Sorted Array

来源:互联网 发布:php goto语句 编辑:程序博客网 时间:2024/06/16 13:10

一、题目描述

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.


题目解读:给出一个序列,去掉序列中重复的元素,返回不重复序列的长度n,且数组的前n个元素就是这个不重复序列。


思路:设置两个指针,通过比较两个元素,如果相同就往后移,不相同就赋值到前面元素的位置。


c++代码(40ms,20.83%)

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int len = nums.size();        if(len == 0 || len == 1)            return len;        int start = 0;        int end = 1;        while(end < len){            while((nums[start] == nums[end]) && (end<len)){                end++;            }            if(end<len){                nums[start+1]=nums[end];            }            if(end>=len && nums[start] == nums[end-1])                break;            start++;            end++;        }        return start+1;        }};


一份更简洁的代码(34ms,40.26%)

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


0 0
原创粉丝点击