Two similar nearest number

Source: Internet
Author: User

Returns an array with N numbers and finds two numbers in the array so that the sum of the two numbers is close to 0.

Http://www.cnblogs.com/haolujun/archive/2012/10/12/2721874.html

This article provides several algorithms, including brute-force algorithms, that traverse every two numbers to obtain the minimum value and the complexity is n square.

There is a better way to sort data first, traverse each positive number (or negative number), traverse to a number, use this number to take negative, and perform binary search in the area opposite to the symbol, find the nearest number.

My method is to use hash to separate positive and negative numbers into a hash table, and negative numbers take the absolute value. Traverse each element of a hash table to the corresponding position of another hash table and traverse the two ends to find the nearest number.

This method saves the complexity of sorting, but it may take some time to traverse the front and back, you can optimize it properly. For example, if the closest distance is d, then the next number is as far as the distance is D, because it makes no sense, this can save some time.

 

A similar question:How to compare two arrays to obtain the closest value of each value to another value

1. Both arrays are sorted, traversing each number of an array and performing binary search on this number to another array.

2. The two arrays are hashed to two hash tables and then scanned before and after the corresponding positions.

Therefore, for the method of finding the nearest one-dimensional array, it is basically necessary to make it orderly and then search according to the characteristics.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.