[leetcode]: 26. Remove Duplicates from Sorted Array

来源:互联网 发布:mysql affected rows 编辑:程序博客网 时间:2024/06/11 00:27

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.分析

因为是排序好的,所以只需要顺序遍历一遍。
用一个newindex来标记新的数组元素的下表。

3.代码

int removeDuplicates(vector<int>& nums) {    if (nums.size() < 2)        return nums.size();    int newIndex = 1;    for (int i = 1; i < nums.size(); i++) {        if (nums[i] != lastValue)            nums[newIndex++] = nums[i];    }    return newIndex;}
原创粉丝点击