In the town of Digitville, there was a list of numbers called nums
containing integers from 0 to n - 1. Each number was supposed to appear
exactly once in the list, however, two mischievous numbers sneaked in an additional time , making the list longer than usual.
As the town detective, your task is to find these two sneaky numbers. Return an array of size two containing the two numbers (in any order), so peace can return to Digitville.
#include<vector>usingnamespace std;
classSolution {
public: vector<int> findDuplicates(vector<int>& nums) {
int n = nums.size();
vector<int> cnt(n, 0), res;
for (int x : nums) ++cnt[x];
for (int i =0; i < n; ++i) if (cnt[i] ==2) res.push_back(i);
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;
classSolution {
publicint[]findDuplicates(int[] nums) {
int n = nums.length;
int[] cnt =newint[n];
for (int x : nums) cnt[x]++;
int[] res =newint[2];
int idx = 0;
for (int i = 0; i < n; ++i) if (cnt[i]== 2) res[idx++]= i;
return res;
}
}
1
2
3
4
5
6
from typing import List
classSolution:
deffindDuplicates(self, nums: List[int]) -> List[int]:
from collections import Counter
count = Counter(nums)
return [x for x in count if count[x] ==2]