Leetcode 26. Remove Duplicates from Sorted Array
来源:互联网 发布:mysql修复数据表 编辑:程序博客网 时间:2024/06/06 06:43
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 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
思路:
1. 把重复的数交换到后面去。维持一个长度逐渐增加的起始位置变化的多余的elements,例如:
1,1,1,2,2,3,4,4
当遍历到第二个1,发现等于当前最大值(=1),则需要用left指针指向这个位置,然后用right指针从这里继续遍历;当right指针遇到2,则更新最大值等于2,且让right指向的数和left指向的数交换,left往后移动一下,right继续移动;当right指向的值还=2,等于最大值,不需要移动left;
2. two pointer:这里是两个指针都从左边移动,昨天遇到的情况是一个左边,一个右边,都往中间移动!形式不同,但都是two pointer
//two pointerclass Solution {public: int removeDuplicates(vector<int>& nums) { // int left=0,right=0; int mx=INT_MIN; for(int right=0;right<nums.size();right++){ if(nums[right]>mx){ mx=nums[right]; swap(nums[left],nums[right]); left++; } } return left; }};
- [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
- 【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
- 26. Remove Duplicates from Sorted Array LeetCode
- 【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
- LeetCode - 26. Remove Duplicates from Sorted Array
- leetcode-26. Remove Duplicates from Sorted Array
- 26.[Leetcode]Remove Duplicates from Sorted Array
- spring装配bean(基于注解)
- 深入浅出讲解:php的socket通信
- Cocos Creator使用小记
- eclipse没有(添加)"Dynamic Web Project"选项的方法
- HDU2044 一只小蜜蜂...
- Leetcode 26. Remove Duplicates from Sorted Array
- 游戏编程中的人工智能技术一书的附录
- ZK设计原理简述
- Oracle监控的关键指标有哪些
- 深入浅出讲解:php的socket通信_0
- block学习总结
- 使用 Socket 通信实现 FTP 客户端程序
- C++ primer-练习6.22
- LeetCode钻研9 判断链表是否有环