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