LeetCode 506. Relative Ranks

来源:互联网 发布:淘宝如何开天猫店 编辑:程序博客网 时间:2024/05/16 01:29

506. Relative Ranks

Description

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:1.N is a positive integer and won't exceed 10,000.2.All the scores of athletes are guaranteed to be unique.

Solution

  • 题意即对于一个数组,给出每一个数在这个数组中是第几大的数,对于前三名,要特殊给出“Gold Medal”、“Silver Medal”、“Bronze Medal”。
  • 我的做法就是遍历这个数组,通过二分查找(在此之前,已复制到一个有序数组中)来查询这个数是第几大。
  • 代码如下。
int mycmp(const void *a,const void *b){    return *(int*)a - *(int*)b;}int findRank(int *nums,int len,int target){    int l = 0,r = len - 1;    int mid = (l + r) / 2;    while (l < r) {        if (nums[mid] == target)            return len - mid;        else if (nums[mid] > target)            r--;        else             l++;        mid = (l + r) / 2;    }    return len - mid;}char** findRelativeRanks(int* nums, int numsSize, int* returnSize) {    char **rnt = (char **)malloc(sizeof(char *) * (numsSize + 1));    for (int i = 0;i < numsSize;i++)        rnt[i] = (char *)malloc(sizeof(char) * 10);    int *snums = (int *)malloc(sizeof(int) * numsSize);    memcpy(snums,nums,numsSize * sizeof(int));    qsort(snums,numsSize,sizeof(int),mycmp);    for (int i = 0;i < numsSize;i++) {        int rank = findRank(snums,numsSize,nums[i]);        if (rank == 1)            strcpy(rnt[i],"Gold Medal");        else if (rank == 2)             strcpy(rnt[i],"Silver Medal");        else if (rank == 3)            strcpy(rnt[i],"Bronze Medal");        else             sprintf(rnt[i],"%d",rank);    }    *returnSize = numsSize;    return rnt;}
  • 用优先队列也可以快速找到排名,但是需要一个下标来辅助/
  • 优先队列用first元素来排序,保证队列头总是分数最高的那一个,而second元素则记录了他在原数组中的位置,从而进行更新,代码如下(题解摘录,侵删)。
class Solution {public:    vector<string> findRelativeRanks(vector<int>& nums) {        priority_queue<pair<int,int> > pq;        for(int i=0;i<nums.size();i++)        {            pq.push(make_pair(nums[i],i));        }        vector<string> res(nums.size(),"");        int count = 1;        for(int i=0; i<nums.size();i++)        {            if(count==1) {res[pq.top().second] = "Gold Medal"; count++;}            else if(count==2) {res[pq.top().second] = "Silver Medal"; count++;}            else if(count==3) {res[pq.top().second] = "Bronze Medal"; count++;}            else {res[pq.top().second] = to_string(count); count++;}            pq.pop();        }        return res;    }};
原创粉丝点击