Given an array of integers, find the first pair whose sum equals the given number.
Example:
Given array [14, 8, 5, 7, 4, 1, 20] and number 12, return (5, 7).
Clarification:
The term "first pair" means the both 2 numbers appear before the latter of any other pair. In above example, the first pair is (5, 7) instead of (8, 4).
Thinking:
A typical way to find if there are 2 elements in an array such that their sum is a given number is that sort the array first, and then use an auxiliary array and 2 pointers (or something alike, like array indices), scanning the 2 arrays once. The bottleneck of this approach is sorting, and its complexity is \(O(n\log n)\).
But the problem here is to find the first pair, which increases the difficulty. At a glance, sorting may destroy the order of elements in original array, and if doing so, we'll have no idea which pair is the right one. Following this acknowledgement, we may only use a brute-force approach to check each pair by order. Although an auxiliary array can be made use of, but that will also take \(O(n^2)\) in time, with no real improvement.
Although there IS a better way (post here) to do this problem, this post just shows the brute-force code and it's not so ugly.
Related Posts:
\(O(n\log n)\) Approach to Solve this Problem
No comments:
Post a Comment