【Lintcode】1615. The Result of Investment
題目地址:
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)。
相關文章
- print the result sqlSQL
- OGEM Solids Control New Investment doubled the production capacitySolid
- jQuery event.resultjQuery
- Oracle Query Result CacheOracle
- Oracle 11.2.0.1 Result Cache 測試 - 12 DBMS_RESULT_CACHE管理包Oracle
- FileReader result 屬性
- 淺談Oracle Result CacheOracle
- How to check payroll result is posted?
- Numercial result of ADFP
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- attempt to index local ‘result‘ (a nil value)Index
- mysqldump --result-file引數MySql
- [iOS]This will result in loss of keychain access ?iOSAI
- [LintCode] Permutation in String
- LintCode 主元素 II
- LintCode 解碼方法
- LintCode-Search for a Range
- LintCode-K Sum
- LintCode-Word SegmentationSegmentation
- LintCode-Hash FunctionFunction
- LintCode-Fast PowerAST
- Lintcode-Max Tree
- LintCode-Partition Array
- LintCode-Subarray Sum
- LintCode-Majority Number
- LintCode-A+B Problem
- LintCode-BackPack II
- LintCode-Previous Permuation
- LintCode 字串比較字串
- query result cache in oracle 11gOracle
- struts2 result type型別型別
- How to use sql result stored on shell variable?SQL
- Result Sets from Stored Procedures In Oracle (轉)Oracle
- Numercial result of irRMILrp-CGP
- SciTech-Theory-Concept:natural+common -> Principle:process+research+investment -> Definition -> Theory -> Axiom