Re: [閒聊] 每日leetcode

作者: JerryChungYC (JerryChung)   2024-09-18 04:35:43
※ 引述《sustainer123 (溫水佳樹的兄長大人)》之銘言:
: ※ 引述《enmeitiryous (enmeitiryous)》之銘言:
: : 今天是easy 版主好像開票到四點真是辛苦了
: : 題目: 884. Uncommon Words from Two Sentences
: : 給你兩個字串s1 s2,找出其中只出現過一次的單字
: : 思路:照做,用unordered map紀錄字串中空隔間開的單字出現次數最後只回傳出現過一次
: : 的
: : vector<string> uncommonFromSentences(string s1, string s2) {
: : unordered_map<string,int> pre_ans;
: : string temp="";
: : for(int i=0;i<s1.size();++i){
: : if(s1[i]!=' '){
: : temp+=s1[i];
: : }
: : else{
: : pre_ans[temp]++;
: : temp="";
: : }
: : }
: : pre_ans[temp]++;
: : temp="";
: : for(int i=0;i<s2.size();++i){
: : if(s2[i]!=' '){
: : temp+=s2[i];
: : }
: : else{
: : pre_ans[temp]++;
: : temp="";
: : }
: : }
: : pre_ans[temp]++;
: : vector<string> ans;
: : for(auto k:pre_ans){
: : if(k.second==1){
: : ans.push_back(k.first);
: : }
: : }
: : return ans;
: : }
: 思路:
: 照做 太久沒刷題 前面變數還打錯 debug搞了五分鐘才發現
: Python Code:
: class Solution:
: def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
: l1 = s1.split()
: l2 = s2.split()
: result = []
: for w in l1:
: if w not in l2 and l1.count(w) == 1:
: result.append(w)
: for w in l2:
: if w not in l1 and l2.count(w) == 1:
: result.append(w)
: return result
思路:不知道
原本想抄抄貼上睡覺去 想說是Easy就來解一下好了
然後不曉得為啥這能跑到 19ms 就來發個文
偷看到前兩行 就懶得想變數名了
Python Code:
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
l1 = s1.split(' ')
l2 = s2.split(' ')
d1 = defaultdict(int)
d2 = defaultdict(int)
set_1 = set(l1)
set_2 = set(l2)
for a in l1:
d1[a] += 1
if (d1[a] > 1 or a in l2) and a in set_1:
set_1.remove(a)
for b in l2:
d2[b] += 1
if (d2[b] > 1 or b in l1) and b in set_2:
set_2.remove(b)
return list(set_1) + list(set_2)
所以為啥能 19ms (99.69%)
不過又測了幾次 一樣的程式碼還會飆到 41ms (17.98%) 看來沒啥參考性 睡覺實在
晚晚晚 (
作者: sustainer123 (caster)   2024-09-18 07:11:00
大佬

Links booklink

Contact Us: admin [ a t ] ucptt.com