开发者

Array handling Algorithms [closed]

开发者 https://www.devze.com 2023-02-03 02:54 出处:网络
It's difficult to tell what is being 开发者_如何学编程asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current for
It's difficult to tell what is being 开发者_如何学编程asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消