LeetCode Remove Duplicates from Sorted Array 移除有序数列的重复元素
来源:互联网 发布:机锋刹那版主淘宝店 编辑:程序博客网 时间:2024/04/29 23:52
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]
.
小心令人抓狂的下标!
方法一:
class Solution {public: int removeDuplicates(int A[], int n) { if(n<=1) return n; int j = 0; for (int i = 1; i < n; ++i) { if (A[i] != A[j]) { A[++j] = A[i]; } } return ++j; }};
方法二:
class Solution {public:int removeDuplicates(int A[], int n) {if(n<=1) return n;int dup = 0;int i = 1;for (; i < n; i++){if(A[i] == A[i-1]) dup++;else if(dup != 0){for (int j = i; j < n; j++){A[j-dup] = A[j];}n -= dup;i -= dup;dup = 0;}}if(dup != 0){A[n-dup-1] = A[n-1];n -= dup;dup = 0;}return n;}};
C++ STL
template <class ForwardIterator> ForwardIterator unique (ForwardIterator first, ForwardIterator last){ if (first==last) return last; ForwardIterator result = first; while (++first != last) { if (!(*result == *first)) // or: if (!pred(*result,*first)) for version (2) *(++result)=*first; } return ++result;}
//2014-1-25class Solution {public:int removeDuplicates(int A[], int n) {int i = 1, j = 1;for ( ; j < n; j++){if (A[j] != A[j-1]) A[i++] = A[j];}return n? i:0;}};
- LeetCode Remove Duplicates from Sorted Array 移除有序数列的重复元素
- leetcode 4. 移除有序数组中的重复元素 Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array--从有序数组中移除重复元素
- 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-26] Remove Duplicates from Sorted Array(移除数组重复元素)
- [leetcode 26]Remove Duplicates from Sorted Array——移除排序数组中重复元素
- Remove Duplicates from Sorted Array II 从有序数组里移除重复出现元素,最多重复出现2次 @LeetCode
- Remove Duplicates from Sorted Array(去掉重复的元素)leetcode
- Remove Duplicates from Sorted Array II 移除重复的元素(重)
- Remove Duplicates from Sorted Array 有序数组删除重复元素 @LeetCode
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- Leetcode 80. Remove Duplicates from Sorted Array II(从已排序数组中移除重复元素)
- Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)
- Remove Duplicates from Sorted Array——移除排序数组中重复元素
- 【四圣龙神录】 开源仿东方 弹幕射击游戏教程 官网(译)以及国内参考翻译资料
- EPICS入门与安装
- FZU 2135 && FOJ11月赛D题 模拟题
- (阶段三 dijkstra算法温习1.5)HDU 2680 Choose the best route(使用dijkstra算法求解多源起点的最短路径问题)
- 可执行文件的包含信息
- LeetCode Remove Duplicates from Sorted Array 移除有序数列的重复元素
- C语言打印统计单词长度的直方图<The C Programming Language>课后习题
- FZU 2135 && FOJ11月赛E题
- python 中List 与dictionary
- HTML文本框 圆角显示 样式设置方法
- C++ primer读书笔记——5.12 类型转换
- 网页视频插件
- __asm__ __volatile__ GCC的内嵌汇编语法 AT&T汇编语言语法(一)
- JavaScript学习篇之——DOM学习