Given an array of integers, 1 ≤ a[i] ≤ n (n = size of the array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Find all the elements that appear twice in this array.
Example:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.List;public class FindAllDuplicates {public static void main(String[] args) {int[] arr = { 4, 3, 2, 7, 8, 2, 3, 1 };List<Integer> res = findDuplicates(arr);System.out.println(Arrays.asList(res));}static List<Integer> findDuplicates(int[] nums) {List<Integer> v = new ArrayList<Integer>();HashSet<Integer> st = new HashSet<Integer>();for (int i = 0; i < nums.length; i++) {if (st.contains(nums[i]))v.add(nums[i]);st.add(nums[i]);}return v;}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> findDuplicates(vector<int> &nums){vector<int> v;set<int> st;for (int i = 0; i < nums.size(); i++){int x = st.size();st.insert(nums[i]);if (x == st.size())v.push_back(nums[i]);}return v;}int main(){vector<int> arr = {4, 3, 2, 7, 8, 2, 3, 1};vector<int> res = findDuplicates(arr);cout << "[";for (int i = 0; i < res.size() - 1; i++)cout << res[i] << ",";cout << res[res.size() - 1] << "]";return 0;}
No comments:
Post a Comment