Exemple #1
0
    public void Add(HeapVal val)
    {
        currSize++;

        heap[currSize] = val;
        SiftUp();
    }
Exemple #2
0
    private void Swap(int sourceIdx, int destIdx)
    {
        HeapVal temp = heap[sourceIdx];

        heap[sourceIdx] = heap[destIdx];
        heap[destIdx]   = temp;
    }
Exemple #3
0
    public int[] DailyTemperatures(int[] T)
    {
        if (T == null || T.Length == 0)
        {
            return(new int[0]);
        }
        else if (T.Length == 1)
        {
            return(new int[] { 0 });
        }

        MinHeap tempHeap = new MinHeap(T.Length);

        int[] results = new int[T.Length];

        // Run through the temps, storing unmatched (no higher yet found) temps in a MinHeap.
        // When we find a higher temperature than the top of the minheap, keep removing from the MinHeap
        // until we reach an equal/higher temp on the heap.
        tempHeap.Add(new HeapVal(T[0], 0));

        for (int i = 1; i < T.Length; i++)
        {
            while (tempHeap.Length > 0)
            {
                HeapVal minVal = tempHeap.Peek();

                if (minVal.temp >= T[i])
                {
                    break;
                }

                // Otherwise, pop the top of our heap and update that array idx.
                tempHeap.Remove();
                results[minVal.arrayIdx] = i - minVal.arrayIdx;
            }

            // Finally, add this temp to the heap.
            tempHeap.Add(new HeapVal(T[i], i));
        }

        // Add the remaining entries in the heap as 0 entries in our result array as we didn't find matching values.
        while (tempHeap.Length > 0)
        {
            HeapVal minVal = tempHeap.Remove();

            results[minVal.arrayIdx] = 0;
        }

        return(results);
    }