Q:

Write a method that checks if there is at least on pair of numbers which sum equals target

0
Write a method that checks if there is at least on pair of numbers which sum equals target.

arr=[1, 3, 4] and target=5 result is true because the pair (1,4) sums to five.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

public Boolean sumsToTarget(Integer[] arr, Integer target) {
 Map<Integer, Integer> numMap = new HashMap<>();
  for (int i = 0; i < arr.length; i++) {
    int complement = target - arr[i];
    if (numMap.containsKey(complement)) {
      return true;
    } else {
      numMap.put(arr[i], i);
    }
  }
return false;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now