Array handling Algorithms [closed]
Given an array of integers, give two integers from the array whose addition gives a number N.
This was recently covered on the ihas1337code blog. See the comments section for solutions.
Essentially the most efficient way to solve this is to put the numbers in a hash_map and then loop through the array a second time checking each element x if element (N - x) exists in the hash_map.
You can optimize a bit from there, but that is the general idea.
Follow these steps:
1.Sort the numbers using merge sort in O(n logn) in descending order(can be ascending also but for this text assumed them to be sorted in desceending order).
2.Use two pointer variables one pointing to starting element (say p1) and other pointing to last element( say p2).
3.Now add *p1 + *p2 ( temp_sum= *p1 + *p2 ) and compare it with required sum
Repeat these steps untill p1>p2
i.If sum ==temp_sum then our job is over .
ii.If sum > temp_sum then decrease p2 to make it point to a bigger value then its current value so that temp_sum can increase.
iii.If sum < temp_sum then decrease p1 to make it point to a smaller value then its current value so that temp_sum can decrease.
精彩评论