lundi 25 mai 2020

Converting C++ maps to Java map

consider the following cpp code

string ans = "NO";
map<int,vi> idv ; //vi is vector of int

for(int i=1;i<=n;i++)
  idv.[arr[i]].push_back(i);

//frequecy >= 3
for(auto el:idv){
   if(el.ss.size() >= 3){
      ans = "YES";}
}

//non adjecent equal elements
for(auto el:idv)
{
   if(el.ss.size() == 2 && el.ss[0] != el.ss[1]-1)
    {
      ans = "YES";
    }
}

cout<<ans<<endl;

My java translation code

                String ans = "NO";
                Map<Integer,List<Integer>> map = new HashMap<>();
                for (int i : arr) {
                    // map.merge(i,1,Integer::sum);
                    // map.put(i, )
                    List<Integer> temp = map.getOrDefault(i, new ArrayList<>());
                    temp.add(i);
                    map.put(i,temp);

                }

                //check for freq 3
                for (Map.Entry<Integer,List<Integer>> e : map.entrySet()) 
                {
                    if(e.getValue().size() == 3)     
                        ans ="YES";
                }

                //freq 2 and pos change 
                for (Map.Entry<Integer,List<Integer>> i : map.entrySet()) 
                {
                    if(i.getValue().size() == 2 && i.getValue().get(0) != i.getValue().get(1) - 1)
                        ans = "YES";    
                }

                System.out.println(ans);

Input arr[]

1 2 1
1 2 2 3 2
1 1 2
1 2 2 1
1 1 2 2 3 3 4 4 5 5

Output

YES
YES
NO
YES
NO

But Its not working properly as intended. Please can anyone tell me how to do it more efficiently. Also for the in first loop I think I could use map.merge. If anyone knows how to do it please let me know . Thanks ✌️

Aucun commentaire:

Enregistrer un commentaire