-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProblem-2.java
61 lines (47 loc) · 1.4 KB
/
Problem-2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* @author AkashGoyal
* @date 08/06/2021
*/
/**
--------------------- Problem----------->> Common elements in all rows of a given matrix
Problem Link :- https://www.codingninjas.com/codestudio/problems/common-elements-present-in-all-rows-of-a-matrix_1118111
Concept:- Use hashmap to solve this problem
*/
import java.util.*;
public class Solution
{
public static ArrayList<Integer> findCommonElements(ArrayList<ArrayList<Integer>> mat)
{
// Write your code here.
HashMap<Integer,Integer>hmap=new HashMap<>();
for(int i=0;i<mat.size();i++)
{
for(int j=0;j<mat.get(0).size();j++)
{
if(i==0)
{
if(!hmap.containsKey(mat.get(i).get(j)))
{
hmap.put(mat.get(i).get(j),1);
}
}
else
{
if(hmap.containsKey(mat.get(i).get(j)) && hmap.get(mat.get(i).get(j))==i)
{
hmap.put(mat.get(i).get(j),i+1);
}
}
}
}
ArrayList<Integer>alist=new ArrayList<>();
for(Map.Entry map:hmap.entrySet())
{
if((int)map.getValue()==mat.size())
{
alist.add((int)map.getKey());
}
}
return alist;
}
}