LeetCode 26. Remove Duplicates from Sorted Array
Posted on 2016-09-18 16:10 CSU蛋李 阅读(116) 评论(0) 编辑 收藏 举报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.
Subscribe to see which companies asked this question
给你一个已经排好序的数组,让你去掉中间重复的元素,注意:不能用额外的空间再建一个数组,你必须在一个固定的内存中,返回值为新的数组长度,只要数组的开头是
删减后的数组就行,后面的不管
我们第一想到的就是建立一个前驱,如果等于前驱,就把后面的数组元素前移,遍历完全即可,但是这样的时间复杂度为O(n*n),提交后会超出时间限制
再思考,我们就会遇到重复的并不着急前移,统计好这个元素前面有多少重复元素假设为N,直接前移N的单位即可,时间复杂度为O(n)
class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.size() < 2)return nums.size(); int pre = nums[0]; int count = 0; for (int i = 1;i < nums.size();++i) { if (nums[i] == pre) { ++count; } else { nums[i - count] = nums[i]; pre = nums[i]; } } return nums.size() - count; } };