In an array A
of size 2N
, there are N+1
unique elements and exactly one of these elements is repeated N
times.
Example 1:
Input: arr: [1,2,3,3]
Output: 3
Approach
Java
import java.util.HashMap;public class RepeatedNTimes {public static void main(String[] args) {int arr[] = { 1, 2, 3, 3 };System.out.println(repeatedNTimes(arr));}// method to find repeated numberpublic static int repeatedNTimes(int[] A) {HashMap<Integer, Integer> map = new HashMap<>();// iterate till end of elementfor (int i = 0; i < A.length; i++) {// if all-read then return the elemenetif (map.containsKey(A[i])) {return A[i];} else {map.put(A[i], 0);}}return 0;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find repeated numberint repeatedNTimes(int arr[],int n){map<int,int> map;// iterate till end of elementfor (int i = 0; i < n; i++) {// if all-read then return the elemenetif (map.find(arr[i])!=map.end()){return arr[i];} else {map[arr[i]]++;}}return 0;}int main(){int arr[] = { 1, 2, 3, 3 };int n=sizeof(arr)/sizeof(arr[0]);cout<<repeatedNTimes(arr,n)<<"\n";return 0;}
No comments:
Post a Comment