26. Remove Duplicates from Sorted Array

Description

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 by modifying the input array [in-place] with O(1) extra memory.

Example:
Given 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.

Solution

删除有序数组中的重复元素,返回不重复元素的个数k,保证数组前k个位置元素ok就行,后n-k个位置存什么不管

int removeDuplicates(vector& nums) {
    if (nums.empty()) {
        return 0;
    }
    int index = 0;//存放当前未重复数据的最右端位置
    for (int i = 1; i < nums.size(); ++i) {
        if (nums[index] != nums[i]) {//借助数组有序,可以直接遍历去比较
            nums[++index] = nums[i];//如果找到不重复,放到下一个坑里
        }
    }
    return index + 1;
}

你可能感兴趣的:(26. Remove Duplicates from Sorted Array)