即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

【LeetCode】26. Remove Duplicates from Sorted Array

编程语言 zjajgyy 26℃ 0评论
本文目录
[隐藏]

1.题目

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.

2.思路

因为不能使用多余内存,所以用indexOfInsert来记录下一个可以插入的位置,然后从头遍历数组,跳过所有重复的数,将其中一个插入indexOfInsert位置。

3.代码

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int indexOfInsert = 0;
        for (int i=0; iwhile (i+11]) i++;
            nums[indexOfInsert] = nums[i];
            indexOfInsert++;
        }
        return indexOfInsert;
    }
};

转载请注明:CodingBlog » 【LeetCode】26. Remove Duplicates from Sorted Array

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情