Answers for "two sum problem"

C++
1

two sum

class Solution {
    public int[] twoSum(int[] nums, int target) {
      int[] arr = new int[2];
        
        HashSet<Integer> hs = new HashSet<>();
        
        for(int i=0; i<nums.length; i++){
            if(hs.contains(target-nums[i])){
                arr[1] = i;
                break;
            }
            hs.add(nums[i]);
        }
        
        for(int i=0; i<nums.length; i++){
            if(nums[i] == target - nums[arr[1]] && arr[1] != i)
                arr[0] = i;
        }
        return arr;
    }
}
Posted by: Guest on September-02-2021

Browse Popular Code Answers by Language