- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 73 lines of Java from the credited upstream file 3072.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 5 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class FenwickTree {2 public FenwickTree(int n) {3 sums = new int[n + 1];4 }5 6 public void add(int i, int delta) {7 while (i < sums.length) {8 sums[i] += delta;9 i += lowbit(i);10 }11 }12 13 public int get(int i) {14 int sum = 0;15 while (i > 0) {16 sum += sums[i];17 i -= lowbit(i);18 }19 return sum;20 }21 22 private int[] sums;23 24 private static int lowbit(int i) {25 return i & -i;26 }27}28 29class Solution {30 public int[] resultArray(int[] nums) {31 List<Integer> arr1 = new ArrayList<>();32 List<Integer> arr2 = new ArrayList<>();33 Map<Integer, Integer> ranks = getRanks(nums);34 FenwickTree tree1 = new FenwickTree(ranks.size());35 FenwickTree tree2 = new FenwickTree(ranks.size());36 37 add(nums[0], arr1, tree1, ranks);38 add(nums[1], arr2, tree2, ranks);39 40 for (int i = 2; i < nums.length; ++i) {41 final int greaterCount1 = arr1.size() - tree1.get(ranks.get(nums[i]));42 final int greaterCount2 = arr2.size() - tree2.get(ranks.get(nums[i]));43 if (greaterCount1 > greaterCount2)44 add(nums[i], arr1, tree1, ranks);45 else if (greaterCount1 < greaterCount2)46 add(nums[i], arr2, tree2, ranks);47 else if (arr1.size() > arr2.size())48 add(nums[i], arr2, tree2, ranks);49 else50 add(nums[i], arr1, tree1, ranks);51 }52 53 arr1.addAll(arr2);54 return arr1.stream().mapToInt(Integer::intValue).toArray();55 }56 57 private Map<Integer, Integer> getRanks(int[] nums) {58 Map<Integer, Integer> ranks = new HashMap<>();59 SortedSet<Integer> sorted = new TreeSet<>();60 for (final int num : nums)61 sorted.add(num);62 int rank = 0;63 for (Iterator<Integer> it = sorted.iterator(); it.hasNext();)64 ranks.put(it.next(), ++rank);65 return ranks;66 }67 68 private void add(int num, List<Integer> arr, FenwickTree tree, Map<Integer, Integer> ranks) {69 arr.add(num);70 tree.add(ranks.get(num), 1);71 };72}73