Pages

Sunday 30 July 2023

LeetCode - 1 - Two Sum

 class Solution {

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

No comments:

Post a Comment