Remove Duplicates from Sorted Array--从有序数组中移除重复元素
2014-06-22 16:53
651 查看
问题:链接
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 =
Your function should return length =
解答:
两个指针,first指向最后一个非重复元素,last指向未处理的元素的第一位,两个指针都初始化为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 A =
[1,1,2],
Your function should return length =
2, and A is now
[1,2].
解答:
两个指针,first指向最后一个非重复元素,last指向未处理的元素的第一位,两个指针都初始化为0。
代码:
class Solution { public: int removeDuplicates(int A[], int n) { int first,last; first = last = 0; if(n == 0) return 0; while(last != n) { if(A[first] == A[last]) { ++last; } else { A[first+1] = A[last++]; ++first; } } return first+1; } };
相关文章推荐
- LeetCode 26. Remove Duplicates from Sorted Array(移除有序数组的重复元素)
- leetcode 4. 移除有序数组中的重复元素 Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II 从有序数组里移除重复出现元素,最多重复出现2次 @LeetCode
- (有序数组中移除重复元素)Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array 有序数组删除重复元素 @LeetCode
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- Remove Duplicates from Sorted Array——移除排序数组中重复元素
- LeetCode | Remove Duplicates from Sorted Array(删除有序数组的重复元素)
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- [LeetCode-26] Remove Duplicates from Sorted Array(移除数组重复元素)
- LeetCode OJ:Remove Duplicates from Sorted Array II(移除数组中的重复元素II)
- LeetCode 26 Remove Duplicates from Sorted Array (移除有序数组中重复数字)
- leetCode26 Remove Duplicates from Sorted Array(移除多余的重复数组元素)
- LeetCode-Remove Duplicates from Sorted Array-从有序数组移除重复-简单逻辑
- Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)
- Lettcode_26_Remove Duplicates from Sorted Array——移除排序数组中重复元素
- 删除有序数组中的重复元素 Remove Duplicates from Sorted Array
- 【leetcode 移除有序序列重复数字】Remove Duplicates from Sorted Array(List) I(II)
- [LeetCode] Remove Duplicates from Sorted Array 有序数组中去除重复项
- LeetCode 80 Remove Duplicates from Sorted Array II(移除数组中出现两次以上的元素)