1. 程式人生 > >Find All Duplicates in an Array

Find All Duplicates in an Array

range ans span mage num lis div end app

    這道題為簡單題

  題目:

    技術分享

  思路:

    我的思路:定義一個列表ans並初始化,遍歷列表nums,並把nums作為a的索引值,每次加1,最後列表生成器生成ans中==2的索引值

    大神的:同樣定義一個列表,遍歷列表nums,並把x的絕對值-1作為nums索引值判斷是否大於0,如果大於0那麽就表示,這個數目前只出現一次同時nums[abs(x)-1] *= -1,如果小於0那麽表示這個數以前已經出現過,新列表中就添加這個數

  代碼:

    我的:

 1 class Solution(object):
 2     def findDuplicates(self, nums):
3 """ 4 :type nums: List[int] 5 :rtype: List[int] 6 """ 7 ans = [0 for i in xrange(len(nums)+1)] 8 for i in nums: 9 ans[i] += 1 10 return [x for x in xrange(len(nums)+1) if ans[x] == 2]

    大神:

 1 class Solution(object):
 2     def
findDuplicates(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: List[int] 6 """ 7 res = [] 8 for x in nums: 9 if nums[abs(x)-1] < 0: 10 res.append(abs(x)) 11 else: 12 nums[abs(x)-1] *= -1 13
return res

Find All Duplicates in an Array