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?
給定整數(shù)數(shù)組,元素a[i]滿足1 ≤ a[i] ≤ n,一些元素出現(xiàn)兩次、其余的出現(xiàn)一次,請(qǐng)?jiān)诰€性時(shí)間和就地完成的情況下找出出現(xiàn)兩次的元素。
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
思路:
參考 448. Find All Numbers Disappeared in an Array 找出數(shù)組中缺失的數(shù) 的做法,當(dāng)置第i個(gè)數(shù)num[i-1]時(shí),若元素已為負(fù)數(shù),則說明之前出現(xiàn)過。
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res=new ArrayList<>();
for(int i=0;i<nums.length;i++){
int val=Math.abs(nums[i])-1;
if(nums[val]<0) res.add(val+1);
nums[val]=-nums[val];
}
return res;
}
}
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res=[]
for i in range(len(nums)):
val = abs(nums[i])-1
if(nums[val]<0): res.extend([val+1])
nums[val]=-nums[val]
return res