[LeetCode] 26 Remove Duplicates from Sorted Array
2017-09-10 19:54
441 查看
原题地址:
https://leetcode.com/problems/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 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
1and
2respectively. It doesn't matter what you leave beyond the new length.
解法:
先用一个变量记录下每次第一次出现的值,在循环中,每遇到一个大小相同的元素,直接删掉;当大小不等的时候,说明一个新的值已经出现了,就用变量记录下这个新的值的大小。以此类推,直至循环结束。时间复杂度为O(n)。代码如下:
class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.size() == 0) { return 0; } vector<int>::iterator iter = nums.begin(); int first = *iter; iter++; for (; iter != nums.end();) { if (*iter == first) { iter = nums.erase(iter); } else { first = *iter; iter++; } } return nums.size(); } };
于我而言,这题的难度在于把C++的知识都忘掉了,迭代器怎么用都忘了。罪过,罪过。
(这道题的重要点在于怎么把第一次出现的数记录,在什么时候该替换调)
相关文章推荐
- LeetCode 26. Remove Duplicates from Sorted Array && 80. Remove Duplicates from Sorted Array II
- Leetcode 26 Remove Duplicates from Sorted Array
- leetcode:26 Remove Duplicates from Sorted Array-每日编程第二十三题
- leetcode 26 Remove Duplicates from Sorted Array
- 【Leetcode】算法题26 Remove Duplicates from Sorted Array
- LeetCode 26. Remove Duplicates from Sorted Array
- leetCode26 Remove Duplicates from Sorted Array(移除多余的重复数组元素)
- [leetcode] 26. Remove Duplicates from Sorted Array 解题报告
- LeetCode-26-Remove Duplicates from Sorted Array(排序/内部排序)-Easy
- [array] leetCode-26. Remove Duplicates from Sorted Array - Easy
- LeetCode-26-Remove Duplicates from Sorted Array(C语言实现)
- leetcode_question_26 Remove Duplicates from Sorted Array
- leetcode-26. Remove Duplicates from Sorted Array
- leetcode 26 Remove Duplicates from Sorted Array
- leetcode 26. Remove Duplicates from Sorted Array
- 【leetcode】26. Remove Duplicates from Sorted Array
- leetcode题解-26. Remove Duplicates from Sorted Array && 27. Remove Element
- 【leetcode】26. Remove Duplicates from Sorted Array
- LeetCode 26 - Remove Duplicates from Sorted Array
- LeetCode 26. Remove Duplicates from Sorted Array