1. 程式人生 > >506. Relative Ranks(python+cpp)

506. Relative Ranks(python+cpp)

題目:

Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: “Gold Medal”, “Silver Medal” and “Bronze Medal”. Example 1:

Input: [5, 4, 3, 2, 1] 
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] 
Explanation: The first three athletes got the top three highest scores, so they got 
"Gold Medal","Silver Medal" and "Bronze Medal".  For the left two athletes, you 
just need to output their relative ranks according to their scores.

Note: N is a positive integer and won’t exceed 10,000. All the scores of athletes are guaranteed to be unique.

解釋: 先用一個字典記錄原始的值所在的位置,然後降序排序,這樣不用每次都用index()求索引值,真的要學會使用dict來省時間啊。 python暴力解法:

class Solution(object):
    def findRelativeRanks(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
result=['0']*len(nums) sort_nums=sorted(nums)[::-1] flag_g=0 for i in xrange(len(nums)): index=sort_nums.index(nums[i]) if index>2: result[i]=str(index+1) elif index==0: result[i]="Gold Medal" elif
index==1: result[i]="Silver Medal" else: result[i]="Bronze Medal" return result

稍微優美一點的程式碼:

class Solution(object):
    def findRelativeRanks(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        result=['0']*len(nums)
        n=len(nums)
        _dict={}
        for i in range(n):
            _dict[nums[i]]=i
        sorted_nums=sorted(nums,reverse=True)
        for i in range(n):
            if i==0:
                result[_dict[sorted_nums[i]]]="Gold Medal"
            elif i==1:
                result[_dict[sorted_nums[i]]]="Silver Medal"
            elif i==2:
                result[_dict[sorted_nums[i]]]="Bronze Medal"
            else:
                result[_dict[sorted_nums[i]]]=str(i+1)
        return result
        

c++程式碼:

class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& nums) {
        int n=nums.size();
        vector<string> result(n,"");
        map<int,int>_map;
        for(int i=0;i<n;i++)
            _map[nums[i]]=i;
        vector<int>sorted_nums(nums.begin(),nums.end());
        //降序排序
        sort(sorted_nums.begin(),sorted_nums.end(),greater<int>());
        
        for(int i=0;i<n;i++)
        {
            if(i==0)
                result[_map[sorted_nums[i]]]="Gold Medal";
            else if(i==1)
                result[_map[sorted_nums[i]]]="Silver Medal";
            else if(i==2)
                result[_map[sorted_nums[i]]]="Bronze Medal";
            else
                result[_map[sorted_nums[i]]]=to_string(i+1);
        }
        return result; 
    }
};

總結: stl中降序排序不一定非要 sort()reverse(),可以sort(sorted_nums.begin(),sorted_nums.end(),greater<int>());