Java solution


  • 0
    L

    Surprisingly, my O(n^2) beat 100% :). But nonetheless, an O(n) that uses hash.

     public int[] twoSum(int[] nums, int target) {
            Map<Integer,Integer> map = new HashMap();
            for(int i=0;i<nums.length;i++) {
                if(map.containsKey(target-nums[i])) {
                    return new int[] {map.get(target-nums[i]),i};
                }
                map.put(nums[i],i);
            }
            return new int[0];
        }
    

Log in to reply
 

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