題目:https://leetcode.com/problems/find-players-with-zero-or-one-losses/description/
描述:輸入許多比賽勝負結果的資料,分別找出完全沒輸過以及正好輸一場的選手們的編號,輸出結果的編號需要遞增排序好
解題思路:要找出現頻率就是map出場的時間,用HashMap紀錄所有出場選手的敗場次數,再將次數為0跟1的資料找出並排序後輸出即可
程式碼:(HashMap)
class Solution {
public List<List<Integer>> findWinners(int[][] matches) {
Map<Integer, Integer> lostCount = new HashMap<>();
for(int[] match : matches) {
if(!lostCount.containsKey(match[0])) lostCount.put(match[0], 0);
if(lostCount.containsKey(match[1])) lostCount.put(match[1], lostCount.get(match[1])+1);
else lostCount.put(match[1], 1);
}
List<List<Integer>> result = new ArrayList<>();
List<Integer> noLost = new ArrayList<>();
List<Integer> oneLost = new ArrayList<>();
for(int key : lostCount.keySet()) {
if(lostCount.get(key) == 0) noLost.add(key);
if(lostCount.get(key) == 1) oneLost.add(key);
}
Collections.sort(noLost);
Collections.sort(oneLost);
result.add(noLost);
result.add(oneLost);
return result;
}
}
或是也可以採用輸入時會自動排序的TreeMap,這樣在找尋輸出的資料後就不需在進行一次排列,雖然沒有比較快(leetcode中實際用時比用HashMap還慢),不過因為我之前沒用過且TreeMap本身的特性(自動排序的map&底層使用紅黑樹)很實用,以後肯定還有要用到的機會所以先記錄一下
程式碼:(TreeMap)
class Solution {
public List<List<Integer>> findWinners(int[][] matches) {
Map<Integer, Integer> lostCount = new TreeMap<>();
for(int[] match : matches) {
if(!lostCount.containsKey(match[0])) lostCount.put(match[0], 0);
if(lostCount.containsKey(match[1])) lostCount.put(match[1], lostCount.get(match[1])+1);
else lostCount.put(match[1], 1);
}
List<List<Integer>> result = new ArrayList<>();
List<Integer> noLost = new ArrayList<>();
List<Integer> oneLost = new ArrayList<>();
for(int key : lostCount.keySet()) {
if(lostCount.get(key) == 0) noLost.add(key);
if(lostCount.get(key) == 1) oneLost.add(key);
}
result.add(noLost);
result.add(oneLost);
return result;
}
}
時間複雜度:O(nlogn)
空間複雜度:O(n)
leetcode
medium
map/set
red-black tree
題目:https://leetcode.com/problems/power-of-four/description/ 描述:判斷輸入的數字是否為4的次方數 解題思路:標準解法是使用對數基底變換方法,不過這題也可以看作判斷是否為2的次方數的延伸題,4的次方數跟2的次方數一樣用二進位制表示只會有1個位元為1,不過這次這些1只會出現在奇數位上,額外再用一個mask來判斷1是否出現在奇數位即可 程式碼: class Solution { public boolean isPowerOfFour(int n) {
Dec 7, 2022題目:https://leetcode.com/problems/power-of-three/description/ 描述:判斷輸入的數字是否為3的次方數 解題思路(1):用對數的基底變換計算,如果i = log10(n) / log10(3)的i為整數的話代表n為3的次方數 程式碼: class Solution { public boolean isPowerOfThree(int n) {
Dec 7, 2022題目:https://leetcode.com/problems/power-of-two/description/ 描述:判斷輸入的數字是否是2的n次方數 解題思路:有個方法能快速找出正整數n是否為2的n次方數/只有一個位元為1:將n與n-1進行位元AND運算,結果為0則n即為2的n次方數/只有一個位元為1 程式碼: class Solution { public boolean isPowerOfTwo(int n) {
Dec 6, 2022題目:https://leetcode.com/problems/reverse-bits/ 描述:將32位元的unsigned int中的位元順序顛倒後回傳結果的值 解題思路:詳細解答來源,用分治法(divide and conquer)每次將處理範圍中左半與右半邊的位元值互換,對一個有2^n位元的數字總共只需要換n次即可 程式碼: public class Solution { // you need treat n as an unsigned value
Nov 30, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up