Leetcode 442. Find All Duplicates in an Array
来源:互联网 发布:java 垃圾回收 手动 编辑:程序博客网 时间:2024/06/15 17:32
Leetcode 442. Find All Duplicates in an Array
问题描述:
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
以后要注意审题,这次就没注意到1 ≤ a[i] ≤ n (n = size of array)条件,有了这个条件,就可以使用a[i]做下标了
写的第一个版本时间太长排序的方法如下:
class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums = sorted(nums) #print nums #for i in xrange(len(sorted(nums))): #if nums[0] == nums[1] index = 0 while(index != len(nums)): if index+1 <len(nums): if nums[index] == nums[index+1]: index += 1 nums.pop(index) #print(index,nums) return nums[0:index]
后来参考了http://bookshadow.com/weblog/2016/10/25/leetcode-find-all-duplicates-in-an-array/
里面提到一种只遍历一次,通过访问到的数字作为下标,将该下标的数变为数字,这样第二次访问这个下标时,数字内容为负说明访问过两次了,代码如下:
#漏看一个条件 1 ≤ a[i] ≤ n ,这个意味着可以拿a[i]-1作为下标(因为下标从0开始),这样子就方便多了#参考http://bookshadow.com/weblog/2016/10/25/leetcode-find-all-duplicates-in-an-array/#遍历nums,记当前数字为n(取绝对值),将数字n视为下标(因为a[i]∈[1, n])#当n首次出现时,nums[n - 1]乘以-1#当n再次出现时,则nums[n - 1]一定<0,将n加入答案#这样只用遍历一次就能完成class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ result = [] for i in nums: if nums[abs(i)-1] > 0: nums[abs(i)-1] *= -1 #print i,nums else: result.append(abs(i)) #print result return result
这个方法还是很有参考性的,简单快速地完成。
阅读全文
0 0
- [LeetCode]Find All Duplicates in an Array
- LeetCode Find All Duplicates in an Array
- Leetcode Find All Duplicates in an Array
- [Leetcode] Find All Duplicates in an Array
- leetCode-Find All Duplicates in an Array
- [leetcode] 442. Find All Duplicates in an Array
- LeetCode 442. Find All Duplicates in an Array
- leetcode:442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array(LeetCode)
- <leetcode>442. Find All Duplicates in an Array
- [leetcode]442. Find All Duplicates in an Array(java)
- [LeetCode]442. Find All Duplicates in an Array
- Leetcode 442. Find All Duplicates in an Array
- LeetCode笔记:442. Find All Duplicates in an Array
- 【LeetCode】 442. Find All Duplicates in an Array
- [leetcode]442. Find All Duplicates in an Array
- Leetcode 442. Find All Duplicates in an Array
- LeetCode 442. Find All Duplicates in an Array
- [LeetCode]237. Delete Node in a Linked List
- @SpringBootApplication注解
- echarts ajax请求方式
- wp-postviews文章浏览次数与点击排行详解
- msiexec.exe进程在安装sqlserver 2012 sp1后继续运行,增加到约100%CPU
- Leetcode 442. Find All Duplicates in an Array
- 关于js模糊匹配
- linux的poll机制
- js生成随机数(数字+字母)
- iOS 逆向REMOTE HOST IDENTIFICATION HAS CHANGED 问题解决
- 递归——算24
- 计算机视觉:从CV基础到深度学习
- 日期插件 pikaday.js 自己使用的小心得 希望能帮到你们
- 纯原生打造GridView单行横向滑动(宽度自适应在父布局居中),手机屏幕px和dp的互换方法,附禁止滑动的自定义方法