-
-
-
-
- def findDuplicates(self, nums):
- """
- :type nums: List[int]
- :rtype: List[int]
- """
- #res=[]
- nums.sort()
- for i in nums:
- if nums.count(i)==1:
- nums.remove(i)
- for j in nums:
- nums.remove(j)
- return nums
以上是有问题的代码,解决的是以下的问题:
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?
Example:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
时间复杂度很高的方法:
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res=[]
nums.sort()
for i in nums:
if nums.count(i)==2:
res.append(i)
#for j in res:
# res.remove(j)
#return res
res=res[::2]
return res
正确的方法:
class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ res=[] for i in range(len(nums)): index=nums[i]-1 if nums[index]<0: res.append(abs(index+1)) nums[index]=-nums[index] return res
搞不清楚我的方法为啥复杂度那么高。