Tuesday 7 September 2021

BinarySearch - Sum of Two Numbers

[https://binarysearch.com/problems/Sum-of-Two-Numbers](https://binarysearch.com/problems/Sum-of-Two-Numbers) ## Problem Statement Given a list of numbers nums and a number k, return whether any two elements from the list add up to k. You may not use the same element twice. Note: Numbers can be negative or 0. Constraints n ≤ 100,000 where n is the length of nums ## Solution Use unordered_map to store the complement. If it is found, return true. If not, update m[nums[i]]. ``` bool solve(vector& nums, int k) { unordered_map m; for (int i = 0; i < nums.size(); i++) { if (m.count(k - nums[i])) return true; m[nums[i]] = i; } return false; } ```

No comments:

Post a Comment

A Fun Problem - Math

# Problem Statement JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today t...