【Lintcode】1615. The Result of Investment

記錄演算法發表於2020-11-22

題目地址:

https://www.lintcode.com/problem/the-result-of-investment/description

給定一個陣列 A A A,代表一些投資人的投資額,有三家公司 A , B , C A,B,C A,B,C,給定它們的初始資金,接著,每個投資人按次序投資當前資金最少的公司,如果兩個公司資金一樣多,則投資公司名字典序最小的公司。問所有投資人投資完後,每個公司的資金是多少。

思路是堆。每次從堆裡取資金量最少(如果資金量一樣則取公司名字典序最小)的公司,進行投資,累加資金數即可。程式碼如下:

import java.util.PriorityQueue;

public class Solution {
    
    class Pair implements Comparable<Pair> {
        private char ch;
        private int fund;
        
        public Pair(char ch, int fund) {
            this.ch = ch;
            this.fund = fund;
        }
        
        @Override
        public int compareTo(Pair p) {
            if (fund != p.fund) {
                return Integer.compare(fund, p.fund);
            } else {
                return Character.compare(ch, p.ch);
            }
        }
    }
    
    /**
     * @param funds: The investment each time
     * @param a:     The initial funds of A
     * @param b:     The initial funds of B
     * @param c:     The initial funds of C
     * @return: The final funds
     */
    public int[] getAns(int[] funds, int a, int b, int c) {
        // Write your code here
        PriorityQueue<Pair> minHeap = new PriorityQueue<>();
        minHeap.offer(new Pair('A', a));
        minHeap.offer(new Pair('B', b));
        minHeap.offer(new Pair('C', c));
    
        for (int fund : funds) {
            Pair cur = minHeap.poll();
            cur.fund += fund;
            minHeap.offer(cur);
        }
        
        int[] res = new int[3];
        while (!minHeap.isEmpty()) {
            Pair cur = minHeap.poll();
            res[cur.ch - 'A'] = cur.fund;
        }
        
        return res;
    }
}

時間複雜度 O ( l A ) O(l_A) O(lA),空間 O ( 1 ) O(1) O(1)

相關文章