python - Find the total number of triplets when summed are less than a given threshold -


So I'm working on some practice problems and there is a problem in reducing the complexity of different integers An array is given [a] and a threshold value T. Me number of triple i , j , k is such that A [i] & lt; One [ja] and a [i] + a [j] + a [k] & lt; = t . I have found it with the following Python script from O (n ^ 3) to O (n ^ 2 log n) I am thinking that I would not have it adapted any more I can do

  import import import bisect first_line = sys.stdin.readline (). Strip () Split ('') num_numbers = int (first_line [0]) threshold = int (first_line [1]) count = 0 if num_numbers & lt; 3: print number other: numbers = sys.stdin.readline (). Strip (). For the split ('') number = map (int, numbers) numbers.sort () I in xrange (num_numbers - 2): j in xrange (i + 1, num_numbers - 1): k_1 = threshold - (number [i ] + Number [j]) if k_1 & lt; Numbers [J]: Break Other: cross_thresh = bisect.bisect (numbers, k_1) - (J + 1) if cross_threatage & gt; 0: Count + = Cross_thash print count   

In the above example, the first input provides only the number of numbers and thresholds in the line. The next line is a complete list if the list is less than 3, then there can be no three times, so we returned 0. If not, then we read in the complete list of integers, sort them, and then process them in the following ways: We use each I and j (such as I & lt; j) and we calculate the highest value of Kashmir which is the i + j + k & lt; = T . Then we find the index of the first element in the list ( s ) that violates this condition and take all the elements between J and S. and add them to the count in a list of 30,000 elements For, it takes about 7 minutes to run. Is there any way to make it faster?

You are displaying binary search for each (i, j) pair k . Therefore O (n ^ 2 log (n)) .

I can suggest an algorithm whose O (n ^ 2)

Assume that the list is left to right and the elements are numbered from 1 to n . Next is the pseudo code:

  i = 1 to n - 2: j = i + 1 while searching maximum k with binary search j & lt; K: j = j + 1 starts with a maximum of K with linear search k   

due to o (n ^ 2) and no more o (n ^ 3) is because position k is decreasing in the same way, thus with linear scanning, you o (n) Not every (i, j) are not spent for pair. Instead, you're spending the total O (n) time to scan k for each specific i value.

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -