Posts

Binary Search to Find Next Greater Element V

You can use the .BinarySearch method of List<T>. It works well, there is a bit of a trick that you need to do when the return index is negative (just assign it to its complement, ~index). No need to perform the Binary Search "by hand" anymore. Achieves a good NLogN, fast solution. LC suggests a Tree to be used but this approach (two lists, one for even, one for odd) works well. Code is down below, cheers, ACC. Count Smaller Elements With Opposite Parity - LeetCode You are given an integer array  nums  of length  n . The  score  of an index  i  is defined as the number of indices  j  such that: i < j < n nums[j] < nums[i] nums[i]  and  nums[j]  have different parity (one is even and the other is odd). Return an integer array  answer  of length  n , where  answer[i]  is the score of index  i .   Example 1: Input:   nums = [5,2,4,1,3] Output:   [2,1,2,0,0] Explanation: Fo...

Standard Priority Queue VIII: Two Queues

Image
This is an interesting problem where you do need a priority queue in order to simulate the game (remember to use Max-Color as the priority since the dequeuing is based on smaller priorities first), but the tricky part here is that you cannot enqueue in the main loop while each round simulation is going on otherwise you'll starve lower priority colors. Hence in the middle of the main simulation loop, instead of enqueuing, just save off the elements to be enqueued later. I used another pQueue for this reason, but you could have used a different data structure, pQueues are not necessary here. Code is down below, cheers, ACC. Multi Source Flood Fill - LeetCode You are given two integers  n  and  m  representing the number of rows and columns of a grid, respectively. You are also given a 2D integer array  sources , where  sources[i] = [r i , c i , color ​​​​​​​i ]  indicates that the cell  (r i , c i )  is initially colored with  color i . Al...