LEETCODE 506. 相对名次

LEETCODE 506. 相对名次_第1张图片

class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& score) {
        vector<string> answer(score.size());
        unordered_map<int, string> scoreRank;
        vector<int> temp(score.size());
        for (int i = 0; i < score.size(); i++) {
            temp[i] = score[i];
        }

        int leftmin, leftmax, rightmin, rightmax;
        for (int step = 1; step < score.size(); step *= 2) {
            for (leftmin = 0; leftmin < (score.size() - step);leftmin=rightmax){
                leftmax = rightmin = leftmin + step;
                rightmax = rightmin + step;
                if (rightmax > score.size() - 1) {
                    rightmax = score.size() ;
                }
                int i = 0;
                int start = leftmin;
                vector<int> tmp;
                tmp.clear();

                while (rightmin < rightmax && leftmin < leftmax) {
                    if (score[leftmin] >= score[rightmin]) {
                        tmp.push_back(score[leftmin++]);
                    } else
                        tmp.push_back(score[rightmin++]);
                }

                while (leftmin < leftmax) {
                    tmp.push_back(score[leftmin++]);
                }
                while (rightmin < rightmax) {
                    tmp.push_back(score[rightmin++]);
                }
                for (int i = 0; i < tmp.size(); i++) {
                    score[start + i] = tmp[i];
                }
            }

            leftmin = rightmax;
        }

        for (int i = 0; i < score.size(); i++) {
            if ((i + 1) == 1)
                scoreRank[score[i]] = "Gold Medal";
            else if ((i + 1) == 2)
                scoreRank[score[i]] = "Silver Medal";
            else if ((i + 1) == 3)
                scoreRank[score[i]] = "Bronze Medal";
            else
                scoreRank[score[i]] = to_string(i + 1);
        }
        for (int i = 0; i < temp.size(); i++) {
            answer[i] = scoreRank[temp[i]];
        }
        return answer;
    }
};

LEETCODE 506. 相对名次_第2张图片

我看没有人用归并排序的迭代方法做吧…


focus:
1 rightmax设定取不到的值
2 step 加上step也是取不到的值

你可能感兴趣的:(leetcode,算法)