Solution using HashMap


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

Log in to reply
 

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