LeetCode26 Remove Duplicates from Sorted Array(Python字典妙用)
来源:互联网 发布:C语言实现循环链表 编辑:程序博客网 时间:2024/06/03 15:14
LeetCode的第26题是非常简单的一道题目,大意就是给定一个排序好的数组,但是该数组中存在重复元素,要求操作该数组,去掉其中的重复元素,同时统计去重之后数组的长度。原题的做法是使用两个指针,比较对应元素,同时修改数组,附上O(n)Python代码:
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ index = 0 length = len(nums) if length < 2: return length for i in range(1,length): if nums[index] != nums[i]: index += 1 nums[index] = nums[i] index += 1 return index
但是,解决了这个题目之后,我们还可以思考另一个问题,本题麻烦的地方在于要求修改原数组,但方便的地方是给定的数组是排序过的,那现在我们修改一下原题的条件,首先不需要修改原数组,但是数组元素变成无序的,这时候如何解决呢?使用Python里的字典同样可以实现O(n)的效率。代码附上:
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ result = 0 cnt = {} for i in range(len(nums)): if nums[i] not in cnt: cnt[nums[i]] = i return len(cnt)遍历一遍数组,只要不在字典中的就把该元素添加进去,但是对于重复元素,由于字典中已经存在,则不会添加,最后得到的字典的长度就是不重复的元素的个数
0 0
- LeetCode26 Remove Duplicates from Sorted Array(Python字典妙用)
- leetcode26. [Array]Remove Duplicates from Sorted Array
- [LeetCode26]Remove Duplicates from Sorted Array
- Leetcode26-Remove Duplicates from Sorted Array
- LeetCode26:Remove Duplicates from Sorted Array
- Leetcode26 Remove Duplicates from Sorted Array
- leetCode26:Remove Duplicates from Sorted Array
- leetcode26:Remove Duplicates from Sorted Array
- leetcode26. Remove Duplicates from Sorted Array
- [LeetCode26] Remove Duplicates from Sorted Array
- LeetCode26. Remove Duplicates from Sorted Array
- [leetcode26] Remove Duplicates from Sorted Array
- Leetcode26. Remove Duplicates from Sorted Array
- Leetcode26. Remove Duplicates from Sorted Array
- LeetCode26. Remove Duplicates from Sorted Array
- leetcode26:Remove Duplicates from Sorted Array
- leetcode26. Remove Duplicates from Sorted Array
- leetcode26~Remove Duplicates from Sorted Array
- Token的身份验证
- Android自定义控件:类QQ6.7.1侧滑菜单栏效果
- java.lang.ClassNotFoundException: com.fasterxml.jackson.datatype.joda.JodaModule
- polycide,silicide,salicide三者区别
- codevs 1029 遍历问题
- LeetCode26 Remove Duplicates from Sorted Array(Python字典妙用)
- mysql创建数据库并指定字符集
- 获取IOS APP Icon
- 欢迎使用CSDN-markdown编辑器
- npm install报错--error MSB4019: The imported project "E:\Microsoft.Cpp.Default.props" was not found
- JVM内存区域与内存溢出异常
- 在 Tomcat 中配置 SSL/TLS 以支持 HTTPS
- ORA-12516 TNS监听程序找不到符合协议堆栈要求的可用处理程序--解决方法之一
- 学生管理系统java(最基础的)