LeetCode removeDuplicatesFromSortedArray两种解法方法
2016-08-01 10:52
330 查看
// Date : 2016.08.01
// Author : yqtao
// https://github.com/yqtaowhu
/[b]************************************************************************[/b]
*
* 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].
*
*
[b]************************************************************************[/b]/
// Author : yqtao
// https://github.com/yqtaowhu
/[b]************************************************************************[/b]
*
* 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].
*
*
[b]************************************************************************[/b]/
//solution 1:using stl is very easy. class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.empty()) return 0; auto cur=nums.begin(); for (;cur!=nums.end()-1;) { auto next=cur+1; if (*cur==*next) nums.erase(cur); else ++cur; } return nums.size(); } };
//solution 2: 需要注意的是题目中,仅仅说是容器中前面几个数正确即可,因此我们不必要删除每个数 //仅仅是用后一个数去覆盖前一个重复的数即可。 class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.empty()) return 0; int id = 1; for(int i = 1; i < nums.size(); ++i) if(nums[i] != nums[i-1]) nums[id++] = nums[i]; return id; } };
相关文章推荐
- LeetCode(81)RemoveDuplicatesfromSortedArrayII
- leetcode- RemoveDuplicatesfromSortedArray
- leetcode上Remove Duplicates from Sorted Array的C++解法
- 26.RemoveDuplicatesfromSortedArray
- leetCode 26.Remove Duplicates from Sorted Array(删除数组重复点) 解题思路和方法
- Remove Duplicates from Sorted Array基本处理方法和集中优质解法解析
- RemoveDuplicatesfromSortedArray
- LeetCode Remove Duplicates from Sorted Array(C语言O(n)解法)
- leetCode 26.Remove Duplicates from Sorted Array(删除数组反复点) 解题思路和方法
- leetcode26.RemoveDuplicatesfromSortedArray
- leetcode之26. Remove Duplicates from Sorted Array(C++解法)
- RemoveDuplicatesfromSortedArray
- leetcode:Remove Duplicates from Sorted Array菜鸟解法
- leetcode:Remove Duplicates from Sorted Array II 菜鸟解法
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array
- LeetCode25:Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II