TwoSum performance
67

I got the below stats:

Runtime: 7 ms, faster than 45.13% of Java online submissions for Two Sum.

Can anyone please critique the code and advise how to make it more elegant and/or performant?


    public int[] twoSum(int[] nums, int target) {

        final Map<Integer, List<Integer>> originalIndicesMap = setIndicesMap(nums);
        Arrays.sort(nums);
        return getIndicesForTarget(nums, target, originalIndicesMap);
    }

    private int[] getIndicesForTarget(int[] nums, int target, Map<Integer, List<Integer>> originalIndicesMap) {
        int[] indices = new int[2];
        for (int sortedIndex = 0; sortedIndex < nums.length; sortedIndex++) {
            int key = nums[sortedIndex];
            int otherKey = target - key;

            if (originalIndicesMap.containsKey(otherKey)) {

                List<Integer> originalIndicesForKey = originalIndicesMap.get(otherKey);

                // Keys are equal and multiple entries exist so just extract the list's first two (same) elements
                if (key == otherKey && originalIndicesForKey.size() > 1) {
                    indices = originalIndicesForKey.subList(0, 2).stream().mapToInt(Integer::intValue).toArray();
                    return indices;
                } else {
                    indices[0] = originalIndicesMap.get(key).get(0);
                    indices[1] = originalIndicesMap.get(otherKey).get(0);
                    Arrays.sort(indices);
                }

            }
        }
        return indices;
    }


    public Map<Integer, List<Integer>> setIndicesMap(int[] nums) {
        final Map<Integer, List<Integer>> originalIndicesMap = new HashMap<>(nums.length / 2);
        for (int index = 0; index < nums.length; index++) {
            if (originalIndicesMap.containsKey(nums[index])) {
                originalIndicesMap.get(nums[index]).add(index);
            } else {
                final int someIndex = index;
                originalIndicesMap.put(nums[index], new ArrayList<Integer>() {{
                    add(someIndex);
                }});
            }
        }
        return originalIndicesMap;
    }
Comments (1)