26. Remove Duplicates from Sorted Array-Python
来源:互联网 发布:zabbix snmp 端口号 编辑:程序博客网 时间:2024/06/06 05:58
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.
思路
- 设置两个游标
i ,j 分别指向每个元素的索引,和不等元素的索引,初始值都指向index=0的元素; - 遍历list,若后一个元素等于前一个元素且后一个元素未越界,则
i 加1,直到找到不相等或越界; - 如果未越界,且
i 不等于j ,则将nums[i] 移到位置j 处; i 和j 分别加1(不管此时i等不等于j,j都要加1 ),直到i 小于n时退出循环。
Code
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ #this quesion asserts the nums is sorted i=0 #index for nums j=0 #index for different elements n=len(nums) while i<n: while i<n-1 and nums[i+1]==nums[i]: i+=1 # if i<n-1 running here indicates we find nums[i] is inequal to nums[i+1] if i<n and i!=j: nums[j]=nums[i] j+=1 i+=1 return j
阅读全文
2 0
- 26. Remove Duplicates from Sorted Array (python)
- 26. Remove Duplicates from Sorted Array-Python
- [leetcode] Remove Duplicates from Sorted Array python
- Remove Duplicates from Sorted Array python 题解
- Remove Duplicates from Sorted Array [Python]
- Remove Duplicates from Sorted Array [python解]
- Leetcode-Remove Duplicates from Sorted Array-Python
- 26. Remove Duplicates from Sorted Array Leetcode Python
- 26. Remove Duplicates from Sorted Array [easy] (Python)
- [leetcode:python]26.Remove Duplicates from Sorted Array
- [LeetCode]26.Remove Duplicates from Sorted Array
- 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
- 26. Remove Duplicates from Sorted Array
- POJ 1028--Web Navigation
- JVM 性能调优监控工具 jps、jstack、jmap、jhat、jstat、hprof 使用详解
- ERROR 1292 (22007): Incorrect datetime value: '' for column 'end_date' at row 1
- Combination SumⅠ&Ⅱ (第十八周)
- svn安装教程
- 26. Remove Duplicates from Sorted Array-Python
- AOP应用之------事务管理
- 扩展欧几里德算法
- Zend Studio 10.6 +xdebug断点调试PHP
- gis项目启动问题
- Lucene查询方式
- 阿里云dubbo提供者Service启动时默认将方法注册到内网IP
- JDBC工具类及用法
- 【bzoj1003】[ZJOI2006]物流运输