leetcode 26. Remove Duplicates from Sorted Array

来源:互联网 发布:金钻淘宝店有哪些 编辑:程序博客网 时间:2024/06/05 22:36

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.

这道题就是要求去除所有的重复元素,然后统计数量并返回。
最最直接的想法就是使用set,但是题目要求空间复杂度是O(1),所以直接设置一个index表示不重复的元素的下标,同时也是最终的length。

代码如下:

/* * 寻找重复的元素并不断的向前移动 * */public class Solution {    public int removeDuplicates(int[] nums)    {        if(nums.length<=1)            return nums.length;        int res=1;        for(int i=1;i<nums.length;i++)        {            if(nums[i]!=nums[i-1])                nums[res++]=nums[i];        }        return res;    }}

下面是C++做法

代码如下:

#include <iostream>#include <vector>using namespace std;class Solution {public:    int removeDuplicates(vector<int>& nums)     {        if (nums.size() <= 1)            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;    }};
原创粉丝点击