https://leetcode.com/problems/count-of-range-sum/
Given an integer array nums
, return the number of range sums this lie in [lower, upper]
inclusive.
Range sum S(i, j)
nums
i
j
is defined i
as the sum of the elements in between indices and (≤ j
), inclusive.
Note:
A naive algorithm of O(n2) is trivial. You must does better than that.
Example:
Given nums = [-2, 5, -1]
, lower = -2
, upper = 2
,
Return 3
.
The three ranges is: [0, 0]
, [2, 2]
, and [0, 2]
their respective sums are: -2, -1, 2
.
classPair { Public intidx; Public LongVal; PublicPairintIdxLongval) { Super(); This. idx =idx; This. val =Val; } }classPaircomparatorImplementsComparator { Public intCompare (Object O1, Object O2) {pair P1=(pair) O1; Pair P2=(pair) O2; if(P1.val <p2.val) {return-1; } Else { return1; } } } Public classSolution { Public StaticArraylist<pair> Tosortedlist (Long[] sum) {ArrayList<pair> ls =NewArraylist<pair> (); for(inti=0; i<sum.length; ++i) {pair P=Newpair (I, sum[i]); Ls.add (P); } collections.sort (LS,Newpaircomparator ()); returnls; } Public Static intBinarySearch (arraylist<pair> ls,intLintRLongLbLongUbintindex) { if(L >r) {return0; } if(L = =r) {if(Ls.get (L). val >= lb && ls.get (l). Val <= ub && Ls.get (L). IDX >=index) { //System.out.println ("Candidate Index range: [" + Index + "," + Ls.get (L). idx + "]"); return1; } return0; } intrs = 0; intMid = (L + r)/2; if(Ls.get (mid). val <lb) {RS= BinarySearch (ls, mid+1, R, LB, ub, index); } Else if(Ls.get (mid). val >UB) {RS= BinarySearch (LS, L, mid-1, LB, ub, index); } Else{RS= BinarySearch (LS, l, mid-1, LB, UB, index) + binarysearch (LS, mid+1, R, LB, ub, index); if(Ls.get (mid). IDX >=index) { //System.out.println ("Candidate Index range: [" + Index + "," + Ls.get (L). idx + "]");rs++; } } returnrs; } Public intCountrangesum (int[] Nums,intLowerintUpper) { intn =nums.length; if(n = = 0) { return0; } Long[] sum =New Long[n]; sum[0] = Nums[0]; for(intI=1; i<n; ++i) {Sum[i]= Sum[i-1] +Nums[i]; } intrs = 0; ArrayList<pair> ls =tosortedlist (sum); for(inti=0; i<n; ++i) {LongNew_lower = (Long) Lower + sum[i]-(Long) nums[i]; LongNew_upper = (Long) Upper + sum[i]-(Long) nums[i]; intCount = BinarySearch (ls, 0, ls.size ()-1, New_lower, New_upper, i); RS+=count; } returnrs; }}
View Code
[email protected] [327] Count of Range Sum (Binary Search)