[LeetCode]442. Find All Duplicates in an Array
程序员文章站
2024-02-17 11:58:58
...
题目
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]
难度
Medium
方法
因为1=<a[i]<=n
,那么0<=a[i]-1<=n-1
,因此可以将a[i]-1
作为index
。如果a[i]
有2个,那么a[i]-1
会出现2次。当a[i]
第一次出现时,将a[a[i]-1]
置为负值。将i++
,如果a[a[i]-1]
为负数的时候,表示a[i]
之前一定出现过。
由于a[i]
会被置为负数,因此a[a[i]-1]
需要用a[abs(a[i])-1]
python代码
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
duplicates = []
for i in range(len(nums)):
index = abs(nums[i])-1
if nums[index] < 0:
duplicates.append(index+1)
else:
nums[index] = -nums[index]
return duplicates
assert Solution().findDuplicates([4,3,2,7,8,2,3,1]) == [2,3]
assert Solution().findDuplicates([10,2,5,10,9,1,1,4,3,7]) == [10,1]
上一篇: linux中路由、策略路由
下一篇: 我眼中的VRRP 虚拟路由器冗余协议
推荐阅读
-
[LeetCode]442. Find All Duplicates in an Array
-
[LeetCode][Python]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】#26. Remove Duplicates from Sorted Array
-
LeetCode448 — Find All Numbers Disappeared in an Array
-
LeetCode442 — Find All Duplicates in an Array