본문 바로가기
IT/알고리즘

19★] Leetcode 1436. Destination City

by 깻잎쌈 2020. 6. 30.
반응형

최종 목적지를 반환하는 문제.

 

Destination City - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

양 끝점만 한번 나오고 나머지 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;
    }
};
반응형

댓글