Math, asked by shreelabaroi863, 1 year ago

Find four elements a b c and d in an array such that a b c d using hashmap

Answers

Answered by dcepks
0

Answer:

If you know programming in java

then this solution might help you.

Step-by-step explanation:

public static ArrayList<Integer> find(int[] num,int n){

 ArrayList<Integer> ans = new ArrayList<>();

 HashMap<Integer,Pair> hm = new HashMap<>();

 for (int i = 0; i < n; i++) {

  for (int j = i+1; j < n; j++) {

   if (i == j) {

   } else {

    int x = num[i] + num[j];

    if (!hm.containsKey(x)) {

     hm.put(x, new Pair(i, j));

    } else {

     Pair p = hm.get(x);

     ans.add(p.n1);

     ans.add(p.n2);

     ans.add(i);

     ans.add(j);

//      ans.add(e)

     return ans;

     

     

    }

   }

  }

 }

 return new ArrayList<>();

 

}

 

public static class Pair{

 int n1;

 int n2;

 public Pair(int n1,int n2) {

  this.n1 = n1;

  this.n2 = n2;

 }

}

}

Similar questions