題目連接:https://leetcode.com/problems...node
這題實際就是給定範圍內的range sum,divide and conquer的方法。一路計算prefixSum[0:i],並把結果放進tree裏面,而後計算到prefixSum[0:j+1]的時候,找tree裏面有沒有知足條件的prefixSum[0:i],這裏的條件是lower <= sum[0:j+1] - sum[0:i] <= upper
,那麼可知sum[0:j+1] - upper <= sum[0:i] <= sum[0:j+1] - lower
,那麼這個就一個recursion就行了。注意一開始把0加進去,考慮結果是sum[0:j]的狀況,還有要用long型,以避免sum會overflowweb
public class Solution { public int countRangeSum(int[] nums, int lower, int upper) { int n = nums.length; if(n == 0) return 0; // binary search tree Node root = new Node(0); int res = 0; long prefixSum = 0; for(int i = 0; i < n; i++) { prefixSum += nums[i]; res += findNumInBound(root, lower, upper, prefixSum); insert(root, prefixSum); } return res; } private int findNumInBound(Node node, long low, long up, long sum) { // base case if(node == null) return 0; // range: sum - up <= node.val <= sum - low if(node.val < sum - up) return findNumInBound(node.right, low, up, sum); else if(node.val > sum - low) return findNumInBound(node.left, low, up, sum); else return 1 + findNumInBound(node.left, low, up, sum) + findNumInBound(node.right, low, up, sum); } private void insert(Node node, long value) { while(node != null) { if(node.val > value) { if(node.left == null) { node.left = new Node(value); break; } node = node.left; } else { if(node.right == null) { node.right = new Node(value); break; } node = node.right; } } } class Node { long val; Node left; Node right; Node(long val) { this.val = val; } } }
仍是能夠binary index tree來作,要統計sum[0:j+1] - upper <= sum[0:i] <= sum[0:j+1] - lower
範圍內的個數,就是用sum。參考博客:
http://bookshadow.com/weblog/...ide
public class Solution { public int countRangeSum(int[] nums, int lower, int upper) { int n = nums.length; if(n == 0) return 0; // prefix array long[] prefixSum = new long[n]; for(int i = 0; i < n; i++) { prefixSum[i] = (i > 0 ? prefixSum[i-1] : 0) + nums[i]; } long[] sorted = Arrays.copyOf(prefixSum, prefixSum.length); Arrays.sort(sorted); // binary index tree map = new HashMap(); int idx = 1; for(long sum : sorted) { if(!map.containsKey(sum)) map.put(sum, idx++); } // build tree BIT t = new BIT(idx); int res = 0; for(int i = 0; i < n; i++) { int l = binarySearch(sorted, prefixSum[i] - upper - 1); int r = binarySearch(sorted, prefixSum[i] - lower); res += t.sum(r) - t.sum(l); if(prefixSum[i] >= lower && prefixSum[i] <= upper) res += 1; t.add(map.get(prefixSum[i]), 1); } return res; } Map<Long, Integer> map; // find the last element <= val private int binarySearch(long[] arr, long val) { int l = 0, r = arr.length - 1; while(l < r) { int mid = l + (r - l) / 2 + 1; if(arr[mid] <= val) l = mid; else r = mid - 1; } if(arr[l] > val) return 0; return map.get(arr[l]); } class BIT { int n; int[] tree; BIT(int n) { this.n = n; tree = new int[n]; } protected int sum(int i) { int res = 0; while(i > 0) { res += tree[i]; i -= i & -i; } return res; } protected void add(int i, int val) { while(i < n) { tree[i] += val; i += i & -i; } } } }