【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)。
相關文章
- Numercial result of ADFP
- FileReader result 屬性
- Numercial result of irRMILrp-CGP
- 淺談Oracle Result CacheOracle
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- attempt to index local ‘result‘ (a nil value)Index
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1218. Number Complement
- 【Lintcode】1850. Pick ApplesAPP
- 【Lintcode】572. Music PairsAI
- 【Lintcode】318. Character Grid
- 【Lintcode】1891. Travel Plan
- struts 2 result的type值解釋
- [譯] 如何在 Swift 5 中使用 ResultSwift
- ORA-01489: result of string concatenation is too long
- SciTech-Theory-Concept:natural+common -> Principle:process+research+investment -> Definition -> Theory -> Axiom
- [LintCode/LeetCode] Check Sum of K PrimesLeetCode
- [LintCode]NumberofIslands(島嶼個數)
- lintcode-514-柵欄染色