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?
給定整數數組,元素a[i]滿足1 ≤ a[i] ≤ n,一些元素出現兩次、其余的出現一次,請在線性時間和就地完成的情況下找出出現兩次的元素。
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
思路:
參考 448. Find All Numbers Disappeared in an Array 找出數組中缺失的數 的做法,當置第i個數num[i-1]時,若元素已為負數,則說明之前出現過。
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