LeetCode 26 Remove Duplicates from Sorted Array

来源:互联网 发布:mac用什么五笔 编辑:程序博客网 时间:2024/06/08 09:25

题目:

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.

题目链接

题意:

给一个已经排好序的数组,要求去除其中重复的元素,并返回新的数组的长度。要求不得申请额外的空间。

我们可以用两个指针,一个遍历数组,另一个用于指向下一个不重复的数,当便利数组的指针读取到当前数和前一个数相同时,跳过操作,继续遍历,当读取到不相同,则更新另一个指针所指向的位置的数,将这个不相同的数存在指向的位置,依次向后枚举判断。

代码如下:

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


阅读全文
0 0