leetcode327 (tree-like array/merge sort)

Source: Internet
Author: User

Problem Description :

Given an array of integers, Nums returns the number of intervals that fall within the range of [Low, upper] (including boundaries).
The definition of intervals and sums (I, j) is the and of the elements of all subscripts between I and J (I≤j), including the boundary.

Ideas:

Merge sort

The problem can be described as, for each sums[i], the number of J that satisfies lower<=sums[i]-sums[j]<=upper, and is summed.

A very ingenious way is to sort the sums to get ocums, and then ask Ocums[m]-ocums[n] = sums[i]-sums[j] fall in the upper and lower bounds of the number, here want to emphasize ocums[m],ocums[n] respectively corresponding to the sums[i before the order ],SUMS[J]. The advantage of this is that after sorting the number of elements in the ocums interval to facilitate a lot of, for example, Ocums[m], just find the upper bound of Ocums[y], and just meet the lower bound of the ocums[x],x-y is the number (note ocums is ascending, so x must be greater than Y), Find the upper and lower bounds of the method if you do not use a circular linear lookup (that is, from small to large one by one), you can use the algorithm less complex binary search, this idea is used for merging sorting.

The idea of merging sorting is to divide the interval into the upper and lower two semi-space X and Y, then the number of two spaces to take x[i] and y[j], compare these two numbers, if X[I]

The idea of merging sorting to find all the interval and, is to first divide the interval sums to the smallest, and then to satisfy the interval and the number of upper and lower bounds, and then to order the interval, and then merge two cells, to meet the number of interval and upper and lower bounds, and then the combined interval to sort, and then merge the two interval after sorting Cycle down, from the point of view of a tree, is to start dividing the interval from the root node, counting and sorting from the lowest level, and sorting upward, so this is a recursive process, and the process of finding the number is calculated in the process of merging.

# merge Sort # confusing two points # 1. Why is the minimum only dividing the interval to two numbers sums[i, i+1] instead of a number? # This is because the object of the operation is and, at the same time to follow the lower half interval # when there are only two numbers, the essence is to see nums[i] = sums[i + 1]-sums[i] in the upper and lower bounds # Minimum interval division will not overlap, will not appear sums[i-1, I], there is a number NUMS[I-1] # This number will be considered in the process of merging adjacent two minimum intervals (imagine a binary tree) # 2. After sorting out the sums to get ocums, select the interval and ocums[i]-ocums[j] in the upper and lower bounds, this reasonable # problem also said that the interval and is equal to sums[m]-sums[n], in essence, the range of the source sequence and whether [M, n] satisfies the upper and lower bounds #        This method is really good AH # Finally, this algorithm complexity is n-side, I do not know how to pass the class solution (object): Def countrangesum (self, nums, lower, Upper): "" " : Type Nums:list[int]: type Lower:int:type upper:int:rtype:int "" "Size = le         N (nums) sums = [0] * (size + 1) for x in range (1, size + 1): sums[x] + = Nums[x-1] + sums[x-1]            INF = Max (sums) def mergesort (lo, HI): if lo = = hi:return 0 mi = int (lo + hi)/2) CNT = MergeSort (lo, MI) + mergesort (mi + 1, hi) x = y = Lo for i in range (mi + 1, hi + 1) : While x <= mi and sums[i]-SUMS[X] >= lower:x + = 1 while y <= mi and sums[i]-sums[y] > upper: Y + = 1 cnt + y part = Sums[lo:hi + 1] l, h = lo, MI + 1 F or I in range (lo, hi + 1): x = Part[l-lo] if l <= mi else INF y = Part[h-lo] if h &lt            = Hi Else INF if x < y:l + = 1 else:h + 1 Sums[i] = min (x, y) Return CNT return mergesort (0, size) nums = [-2, 5, 1, 3, 1, -4, 2]lower = -2upper = 2X =solution () print (X.countra Ngesum (Nums, Lower, Upper))

Tree-like array

You can also change the problem on the line, that is, to satisfy sums[i]-upper<=sums[j]<=sums[i]-lower of the number of J, the simplest way is to each sums[i] traverse all (J,j

# Leetcode 327: Find the number of all intervals and between [lower, Upper] # solution 1 KK ...        Complexity n-side, timeout class solution (object): Def countrangesum (self, nums, lower, Upper): "" ": Type Nums:list[int] : Type Lower:int:type upper:int:rtype:int "" "ans = 0 sum = [0 for _ in Nums                ] for I, NUM in enumerate (nums): if i = = 0:sum[i] = num ELSE: Sum[i] = sum[i-1] + num if sum[i] >= Lower and sum[i] <= Upper:ans + = 1 for J in Range (i): if SUM[J] >= (sum[i]-upper) and Sum[j] <= (sum[i]-lower): ans + = 1 return ansnums = [-2, 5, 1, 3, 1, -4, 2]lower = -2upper = 2X =solution () print (X.countrangesum (nums, Lower, Uppe R)) 

But with a more straightforward description is the number of upper that is located (Sums[i]-sums[i, lower]-sums[j), in order to know how many times each value was taken, In which position, of course, the premise is that each order has only the first number of the sequence. That is, for sums[i], simply insert the value of sums[i] into the new sequence (which can be done in binary order). Since our goal is to sum the numbers, we can make the value of the sequence count, then the index of the sequence is sums[i], so that the structure of the tree array is out.

# based on the previous idea, the use of a tree array to reduce complexity # is also to find the number of SUMJ in the interval [Sumi-upper, Sumi-lower], # The previous naive method is for each sumi, direct for J in range (0, I), resulting in an algorithm complexity of O (n^2 # The idea of a tree-like array is to sums a sequence of long m, and then build a tree array with a length of that sequence to record the number of occurrences of each value # so, to calculate the number of SUMJ falling in the interval [Sumi-upper, Sumi-lower], The only reason for the interval and # feasibility of the array is that in the for Sumi in sums loop, the tree array is generated with Sumi, and the current tree array only records (X, x<=i) sumx# for each sumi, the algorithm complexity is O (Logn), The total algorithm complexity is O (NLOGN) Import Bisectclass Solution (object): Def countrangesum (self, nums, lower, Upper): "" ": Ty PE Nums:list[int]: type Lower:int:type upper:int:rtype:int "" "ans = 0 sum            s = [0 for _ in Nums] for I, NUM in enumerate (nums): if i = = 0:sums[i] = num        Else:sums[i] = sums[i-1] + num oscums = sorted (set (sums)) ft = Fenwicktree (len (oscums)) For sumi in sums:left = Bisect.bisect_left (oscums, sumi-upper) right = Bisect.bisect_right (o Scums, sumi-lower) ans + = Ft.getsum (right)-ft.getsum (left) + (lower <= sumi <= Upper) Ft.add (Bisect.bisect_right (Oscums, Sumi), 1)  Return Ansclass Fenwicktree (object): Def __init__ (self, n): # n The length of the array SELF.N = n SELF.C = [0 for _ in range (n + 1)] def lowbit (self, x): Return x & (x ^ (x-1)) def add (self, I, Val): While I & lt;= Self.n:self.c[i] + = val i + = Self.lowbit (i) def getsum (self, i): sum = 0 Whil e i > 0:sum + = self.c[i] I-= self.lowbit (i) return sumnums = [-2, 5, -1]lower = -2upper = 2X =solution () print (X.countrangesum (nums, Lower, Upper))

Reference blog:

http://bookshadow.com/weblog/2016/01/11/leetcode-count-of-range-sum/

leetcode327 (tree-like array/merge sort)

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.