1. 程式人生 > >【LeetCode】未分類(tag裡面沒有)(共題)

【LeetCode】未分類(tag裡面沒有)(共題)

【504】Base 7 (2018年11月25日)

Given an integer, return its base 7 string representation.

Example 1:
Input: 100
Output: "202"

Example 2:
Input: -7
Output: "-10"

Note: The input will be in range of [-1e7, 1e7].

題解:直接按照進位制轉換

 1 class Solution {
 2 public:
 3     string convertToBase7(int
num) { 4 bool negative = false; 5 if (num < 0) { 6 negative = true; 7 num = -num; 8 } 9 string ret = ""; 10 while (num != 0) { 11 int mod = num % 7; 12 num = num / 7; 13 ret = to_string(mod) + ret;
14 } 15 ret = negative ? "-" + ret : ret; 16 ret = ret == "" ? "0" : ret; 17 return ret; 18 } 19 };
View Code

 

【506】Relative Ranks(2018年11月25日)

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.
 1 class Solution {
 2 public:
 3     vector<string> findRelativeRanks(vector<int>& nums) {
 4         const int n = nums.size();
 5         map<int, int, greater<int>> mp;
 6         for (int i = 0; i < nums.size(); ++i) {
 7             int score = nums[i];
 8             mp[score] = i;
 9         }
10         vector<string> ret(n);
11         int cnt = 1;
12         for (auto e : mp) {
13             int idx = e.second;
14             if (cnt <= 3) {
15                 if (cnt == 1) {
16                     ret[idx] = "Gold Medal";
17                 }
18                 if (cnt == 2) {
19                     ret[idx] = "Silver Medal";
20                 }
21                 if (cnt == 3) {
22                     ret[idx] = "Bronze Medal";
23                 }
24                 ++cnt;
25             } else {
26                 ret[idx] = to_string(cnt++);
27             }
28         }
29         return ret;
30     }
31 };
View Code