Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.1 kB
1
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