Array
Last updated
Was this helpful?
Last updated
Was this helpful?
Essentially, this kind of problem can be solved with prefix sum. But search prefix sum takes O(N), how can we accelerate? Use Binary Index Tree(BIT) which guarantee O(logN) for searching an accumulated sum.
So to find the sum of a range, these are typical solutions:
Prefix sum. Works for array: Sum(i, j) = prefixSum[j] - prefixSum[i-1], i is inclusive.
Trick: map.put(0, -1);
, this means Sum(0, i), i.e. prefixSum[i], is what we want.
Binary Index Tree(BIT). When prefixSum1 is known, we need to find another prefixSum2 that meets some constraint, e.g. prefixSum1 - prefixSum = k.
We can also build BST to achieve similar O(logN) search, but worst case is still O(N).
Segment Tree. Mostly used in range sum lookup.(Not used in search cases)
Typicall questions:
: more of a math trick.
Typicall ideas:
Just sort it and iterate
PriorityQueue. When we need to know how many accumulative intervals at some point.
2 sorted arrays: 1 for start points, 1 for end points
1 sorted array to store all points.
Typical questions:
TreeMap is your friend. Calendar problem optimal is O(N).
Greedy:
match nums[i] with i
sliding to find peak or valley
hash map:
1 from left and 1 from right:
Interval problem typically cope with a range: a start point, a end point, and optionally some attributes of this interval, like . It almost always requires sorting. Since it's O(NlogN) anyway, always try TreeMap.
You can store them as array of classes, like .
Alternatively, why not just use . Built-in APIs are amazing!
: Key is how to order multiple points, high->low start points, then low->high end points.
: Key is how to update TreeMap.
2 pointers:
1) sort and skip same value, if (nums[i] == nums[i-1]) continue; 2) when it can't be sort, use array or set at this level;