Single O(n) Java function, you don't need to do two passes


  • 1
    R
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            int curr = nums[i];
            if (table.containsKey(target-curr)) {
                return new int[] {table.get(target-curr), i};
            } else {
                table.put(curr, i);
            }
        }
        return null;
    }
    

Log in to reply
 

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