Untitled

mail@pastecode.io avatar
unknown
java
a month ago
1.1 kB
10
Indexable
Never
import java.util.*;
public class Solution
{
    public List<List<Integer>> findPair(int[] arr)
    {

      Arrays.sort(arr);
         List<List<Integer>> res = new ArrayList<>();

        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {

            map.put(arr[i], i);

        }

        for (int i = 0; i < arr.length - 1; i++) {

            int element = arr[i];

            for (int j = i + 1; j < arr.length; j++) {
                int val = arr[j] - element;

                if (map.containsKey(val)) {
                    int index = map.get(val);

                    if (index == i)
                        continue;

                    List<Integer> list = new ArrayList<>();
                    list.add(arr[i]);
                    list.add(arr[index]);
                    map.remove(arr[i],i);
                    map.remove(arr[index],index);
                    res.add(list);
                }
            }
        }

        return res;


      
    }
}
Leave a Comment