Swift and C++, use dict to record rank and index


  • 0
    X

    for easier understanding, use the same method in both languages:
    Swift:

    class Solution {
        func findRelativeRanks(_ nums: [Int]) -> [String] {
            var result = [String](repeating: "", count: nums.count)
            let len = nums.count
            if len < 1 { return result }
            
            var rankIndex = [Int:Int]()
            for i in 0...len-1 {
                rankIndex[nums[i]] = i
            }
            let rankIndexSorted = rankIndex.sorted { $0.0 > $1.0 } // 0.key > 1.key
            var champion : Int = 1 //counting rank
            var str : String = ""
            for r in rankIndexSorted {
                if champion == 1 { str = "Gold Medal" }
                else if champion == 2 { str = "Silver Medal" }
                else if champion == 3 { str = "Bronze Medal" }
                else { str = String(champion) }
                
                result[r.value] = str
                champion += 1
            }
            return result
        }
    }
    

    C++:

    class Solution {
        public:
        vector<string> findRelativeRanks(vector<int>& nums) {
        
        // A : use map to record [rank : index], them put the rank into [result];
            vector<string> result(nums.size(), "");
            map<int, int> rankIndex;
            for(int i = 0; i < nums.size(); i++){
                rankIndex[nums[i]] = i;
            }
            int champions = 1;
            for(auto i = rankIndex.rbegin(); i != rankIndex.rend(); i++){
                string topStr;
                if(champions==1)      topStr = "Gold Medal";
                else if(champions==2) topStr = "Silver Medal";
                else if(champions==3) topStr = "Bronze Medal";
                else                  topStr = to_string(champions);
        
                result[i->second] = topStr;
        
                champions += 1;
            }
        return result;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.