simple 7 line O(n) java solution using hashmap


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

  • 0
    W

    No need to loop twice actually.

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            Map<Integer,Integer> hm = new HashMap<Integer,Integer>();
            for(int i=0;i<nums.length;i++){
                if(hm.containsKey(target-nums[i]))    return (new int[]{hm.get(target-nums[i]),i});
                else hm.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.