Nine Chapters count judges Net-original website
http://www.jiuzhang.com/problem/67/
Topics
Give a bunch of arrays and a target value, and in this heap of arrays find two numbers that make their sum equal to the target value.
Online testhttp://www.lintcode.com/en/problem/2-sum/
Answer
If the first element in the array of the original problem we use AI to express, the target value we use V to represent.
There are two ways to solve this problem:
Method One:
Since it is necessary to find two numbers to make their and target values, we will think of hash when it comes to finding, because hash can help us to speed up the search method. Then we can sweep through our arrays for a loop, and the hash table is stored in the number of i-1 scanned before the number of times I sweep to the first. So what we are looking for is that there is not an element in front and the number of AI added to V, then we only use in the hash table to find if there is no v-ai this element if there is, then the previous i-1 number has a number plus ai their and v. The time complexity of this method is O (n), and the spatial complexity is O (n).
Method Two:
This method is called two pointers, we can first sort the array, and then two pointers to the array to the end of a single mantissa group of the largest and smallest elements, we call these two pointers front and. If A[front] + a[end] > V, then all the elements on the right side of front +end will be greater than V, so we don't need to consider these elements. So just move the end-1, which is the end pointer, to the left of the array. If A[front] + A[end] < V, then all the elements on the left side of the end +end will be less than V, so we don't have to think about these elements. So just move the front+1, which is the front pointer, to the right of the array. This keeps looping to the front pointer =end the pointer stops. In this way we can find two pointers so that their sum equals v. The time complexity of this method is O (nlogn+n), and the spatial complexity is O (1).
Nine-chapter algorithm surface question 2 sum