Accepted 5 Lines of Java Code (6ms, 98.9%)

  • 0
       public int[] twoSum(int[] nums, int target) {
            HashMap<Integer, Integer> indexMap = new HashMap<>((int)((double)nums.length / 0.75d));
        for (int i = 0; i < nums.length; i++) {
            if (indexMap.containsKey(target - nums[i])) return new int[] { indexMap.get(target - nums[i]), i};
            indexMap.put(nums[i], i);
        return new int[2];

    Some extra time can be gained by initialising the hash map with correct size.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.