Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such, all element appear only once and return the new L Ength.
Do the allocate extra space for another array, and you must does this on place with constant memory.
for example,
Given input array nums = [1,1,2]
,
your function should return length = 2
, with the first elements of nums being 1
and 2
respectively. It doesn ' t matter what are you leave beyond the new length.
Main topic:
Delete a repeating element in an ordered series without applying for another space. Returns the length of the final array.
The code is as follows:
Class solution {public: int removeduplicates (vector<int>& nums) { if (Nums.empty () | | nums.size () == 1) Return nums.size (); int cur = nums[0]; int i = 0; while (I != nums.size () - 1 ) { if (Cur == nums[i+1]) { nums.erase (Nums.begin () + i + 1); &Nbsp; } else { cur = nums[i+1]; i++; } } return nums.size (); }};
If you don't need to delete the element, just count the last number. You can use the following concise approach:
Reference from: Https://discuss.leetcode.com/topic/8907/share-my-clean-c-code
int count = 0;for (int i = 1; i < n; i++) {if (a[i] = = a[i-1]) count++;else a[i-count] = a[i];} return n-count;
Other ideas:
(using extra space, the subject does not apply) put the array elements in the map and then output the map size.
2016-08-11 14:33:57
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1836874
Leetcode 26. Remove duplicates from Sorted array