Remove Duplicates from Sorted Array && Remove Duplicates from Sorted Array II
来源:互联网 发布:社交软件 英文翻译 编辑:程序博客网 时间:2024/06/05 16:03
Remove Duplicates from Sorted Array
移除数组中相同的元素。这题和上题是类似的。
我的思路:
1 有了上题的经验,两个指针移动,相等的时候不做任何动作,循环会让后面的指针一直移动到和前面的指针不相等的时候,再把值赋给前面的指针后一个。注意:一定要判断是空数组的情况,也就是n小于1的时候。
if (n < 1) return n; int start = 0; for (int i = 1; i != n; i++) if (A[start] != A[i]) A[++start] = A[i]; return ++start;
Remove Duplicates from Sorted Array II
我的思路:
1、最多可以有两个相同的。
2、我的思路是设置一个标识来表示出现过没有,如果题目改成了其他条件,我们只需要在判断中修改成相应的数字即可。
3、但是代码还是不够简介,思路不够优化。
我的代码:
int removeDuplicates(int A[], int n) { if (n <= 2) return n; int cur = 0; int duplicate = false; for (int i = 1; i < n; i++) { if (A[cur] != A[i]) { A[++cur] = A[i]; duplicate = false; } else if (!duplicate){ A[++cur] = A[i]; duplicate = true; } } return ++cur;}
别人思路:
1、需要的就是这样的代码,来自leetcode讨论区。
2、这里没有设置什么标志,直接利用下标的差值就可以完成判断。
int removeDuplicates(int A[], int n) { if (n <= 2) return n; // no need to deal with n<=2 case. int len = 2, itor = 2; while (itor < n) { if (A[itor] != A[len-2]) A[len++] = A[itor]; itor++; } return len;}
反思:思路还是不够开
0 0
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove duplicates from sorted array II
- Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- Python logging官方文档链接
- Android Viewpager实现图片轮播(仿优酷效果)
- 【1096】【ZJOI2007】仓库建设 斜率优化DP
- NavigationController覆盖视图
- 什么是位置无关码
- Remove Duplicates from Sorted Array && Remove Duplicates from Sorted Array II
- 使用seajs进行模块化前端开发
- #ifdef __cplusplus extern "C" { #endif 的解释
- How the system configure the default the kernel defconfig
- iOS UITableViewCell重用机制理解之初级剑侠篇(欢迎提建议和分享遇到的问题)
- Android任意时刻从子线程切换到主线程的实现
- 读取sqlserver用户自定义表、视图和存储过程
- BZOJ 3437 小P的牧场 斜率优化DP
- 体会棋盘游戏