반응형
최종 목적지를 반환하는 문제.
양 끝점만 한번 나오고 나머지 city는 두 번씩 나오니까
한 번만 나오는 city 중에 목적지에 있는 city를 반환하는 문제.
class Solution {
public:
string destCity(vector<vector<string>>& paths) {
// 한번나오고 뒤에 배치되어있는 문자열 반환
map<string, int> words;
map<string, int>::iterator it;
for(int i = 0;i<paths.size();i++){
if(( it = words.find(paths[i][0])) == words.end() )
words[paths[i][0]] =1;
else
words[paths[i][0]]++;
if((it = words.find(paths[i][1])) == words.end())
words[paths[i][1]] =1;
else
words[paths[i][1]]++;// ++it->second++;
}
// 한번 나오는 문자열만 넣기
vector<string> cnt;
for ( it = words.begin(); it != words.end() ; ++it )
if(it->second ==1)
cnt.push_back(it->first);
string ans;
for(int i = 0;i<paths.size();i++)
for(int j = 0;j<cnt.size();j++)
if(paths[i][1] == cnt[j])
ans = cnt[j];
return ans;
}
};
앞에 나오면 +1, 뒤에 나오면 -1 해서 최종적으로 -1인 놈 반환
class Solution {
public:
string destCity(vector<vector<string>>& paths) {
map<string, int> words;
map<string, int>::iterator it;
// 앞에 나오면 +1, 뒤에 나오면 -1
for(int i = 0;i<paths.size();i++){
if(( it = words.find(paths[i][0])) == words.end() )
words[paths[i][0]] =1;
else
words[paths[i][0]]++;
if((it = words.find(paths[i][1])) == words.end())
words[paths[i][1]] =-1;
else
words[paths[i][1]]--;
}
// -1인 문자열 반환
vector<string> cnt;
string ans;
for ( it = words.begin(); it != words.end() ; ++it )
if(it->second == -1)
ans = it->first;
return ans;
}
};
반응형
'IT > 알고리즘' 카테고리의 다른 글
21] Leetcode 657. Robot Return to Origin (0) | 2020.07.01 |
---|---|
20] Leetcode 1450. Number of Students Doing Homework at a Given Time (0) | 2020.07.01 |
18] Leetcode 1475. Final Prices With a Special Discount in a Shop (0) | 2020.06.29 |
17] Leetcode 1323. Maximum 69 Number (0) | 2020.06.29 |
16] Leetcode 1252. Cells with Odd Values in a Matrix (0) | 2020.06.27 |
댓글