[Leetcode] Remove duplicates from sorted array 从已排序的数组中删除重复元素
2017-07-01 17:17
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 =[1,1,2],
Your function should return length =2, and A is now[1,2].
题意:除去重复的元素,若有重复只保留一个,返回长度。
思路:遍历数组,用不同的,覆盖相同的。过程:保存第一个元素的下标lo。遇到相等不管,继续遍历,遇到不等的,则将该值赋给lo的下一个,反复这样。代码如下:
1 class Solution 2 { 3 public: 4 int removeDuplicates(int A[],int n) 5 { 6 if(n<=0) return 0; 7 int lo=0; 8 for(int i=1;i<=n-1;++i) 9 { 10 if(A[lo] !=A[i]) 11 A[++lo]=A[i]; 12 } 13 return lo+1; 14 } 15 };
思路相同,另一种写法:
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) 4 { 5 if(n<2) return n; 6 int count=1; 7 int flag=0; 8 for(int i=0;i<n;++i) 9 { 10 if(A[flag] !=A[i]) 11 { 12 A[++flag]=A[i]; 13 count++; 14 } 15 } 16 return count; 17 } 18 };
相关文章推荐
- LeetCode: Remove Duplicates from Sorted Array II(在排序数组中删除重复元素)
- 【LeetCode-面试算法经典-Java实现】【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
- [Leetcode] Remove duplicates from sorted array ii 从已排序的数组中删除重复元素
- leetcode 26. Remove Duplicates from Sorted Array从排序数组中移出重复元素(双指针)
- Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- leetcode 题解:Remove Duplicates from Sorted Array II(已排序数组去三次及以上重复元素)
- LeetCode Remove Duplicates from Sorted Array II 删除整型数组中的重复元素并返回剩下元素个数2
- LeetCode | 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:Remove Duplicates from Sorted Array去掉排序数组中重复的元素
- leetcode:26&80 Remove Duplicates from Sorted Array 删除数组中的重复元素
- LeetCode-Remove Duplicates from Sorted Array II (删除重复元素,使重复次数最多N次)
- LeetCode | Remove Duplicates from Sorted Array II(删除重复的元素2)
- Remove Duplicates from Sorted Array 从排序数组中删除重复
- LinCode Remove Duplicates from Sorted Array 删除排序数组中的重复数字
- leetcode 4. 移除有序数组中的重复元素 Remove Duplicates from Sorted Array
- leetCode 26.Remove Duplicates from Sorted Array(删除数组重复点) 解题思路和方法