【Leetcode周賽】從contest-81開始。(一般是10個contest寫一篇文章)
阿新 • • 發佈:2018-11-08
Contest 81 (2018年11月8日,週四,凌晨)
連結:https://leetcode.com/contest/weekly-contest-81
比賽情況記錄:結果:3/4, ranking: 440/2797。這次題目似乎比較簡單,因為我比賽的時候前三題全做出來了(1:12:39),然後第四題有思路,正在寫,沒寫完,比賽完了寫完提交也對了。
【821】Shortest Distance to a Character(第一題 4分)
給了一個單詞(字串)s,和單詞中的任意一個字母 c,問單詞中的每個字母到 c 的最近距離是多少。
Example 1: Input: S = "loveleetcode", C = 'e' Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
題解:我是用了一個vector記錄了所有字元 c 的下標,然後用遍歷整個字串,用一根指標輔助遍歷 c 下標陣列做的。時間複雜度 O(N)。寫法不夠優秀,c 的下標陣列可以左邊右邊填一個元素,就不用寫那麼多判斷了吧?
1 class Solution { 2 public: 3 vector<int> shortestToChar(string S, charView CodeC) { 4 const int n = S.size(); 5 vector<int> idxs; 6 vector<int> ans(n, -1); 7 for (int i = 0; i < n; ++i) { 8 if (S[i] == C) { 9 idxs.push_back(i); 10 ans[i] = 0; 11 } 12 } 13 intp1 = 0; 14 for (int i = 0; i < n; ++i) { 15 if (p1 == 0 && i < idxs[p1]) { 16 ans[i] = idxs[p1] - i; 17 } else if (p1 + 1 < idxs.size() && i >= idxs[p1] && i <= idxs[p1+1]) { 18 ans[i] = min(abs(i - idxs[p1]), abs(idxs[p1+1] - i)); 19 } else if (p1 + 1 == idxs.size() && idxs[p1] < i) { 20 ans[i] = i - idxs[p1]; 21 } 22 if (p1 + 1 < idxs.size() && i == idxs[p1+1]) { 23 ++p1; 24 } 25 } 26 return ans; 27 } 28 };
【822】Card Flipping Game (第二題 5分)
給了一排紙牌,紙牌前面和後面都有一個數字,我們可以做兩個動作,第一個動作是任意翻動任意的紙牌正反面(形成新的正反面陣列),第二個動作是我們拿一張紙牌,如果它反面的數字沒有在正面的數組裡面出現,那麼這個數字就是good,要求返回最小 good 的數字。
題解:我是先把 front 和 back 數組合二為一,然後把大陣列做了一個排序。然後遍歷正反兩面的陣列,把正反面數字相同的紙牌上的數字放進了一個set裡面,這些數字肯定不是 good 的,因為不論這些紙牌怎麼翻,都是一個數字。然後我返回了大陣列不在set裡面的第一個元素。
1 class Solution { 2 public: 3 int flipgame(vector<int>& fronts, vector<int>& backs) { 4 const int n = fronts.size(); 5 int ans = 0; 6 vector<int> tot(fronts); 7 for (auto b : backs) { 8 tot.push_back(b); 9 } 10 sort(tot.begin(), tot.end()); 11 set<int> st; 12 for (int i = 0; i < n; ++i) { 13 if (fronts[i] == backs[i]) { 14 st.insert(fronts[i]); 15 } 16 } 17 for (int i = 0; i < 2 * n; ++i) { 18 if (st.find(tot[i]) == st.end()) { 19 ans = tot[i]; 20 break; 21 } 22 } 23 return ans; 24 } 25 };View Code
【820】Short Encoding of Words (第三題 6分)
【823】Binary Trees With Factors (第四題 7 分)