26. 删除排序数组中的重复项

题目描述

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 A =[1,1,2],Your function should return length =2, and A is now[1,2].

思路

尾指针的运用,last为前面已经放好的不重复元素序列的尾下标

代码实现

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        
        int n = nums.size();
    	if( n < 1)
    		return 0;
    	int last = 0;
    	for(int i = 1;i < n;i++)
    	{
    		if(nums[i] != nums[last])
    		{	
    			if(last+1 < i)//说明当前元素需要移动
    				nums[last+1] = nums[i];
    			last++;
    		}
    	}

    	return last+1;        
    }
};

posted on 2021-07-24 06:58  朴素贝叶斯  阅读(35)  评论(0编辑  收藏  举报

导航