Construct the Rectangle

class Solution {
public:
    vector<int> constructRectangle(int area) {
        for(int mid = sqrt(area); mid>0; mid--)
            if (!(area%mid))
                return {area/mid, mid};
    }
};
2017/12/11 posted in  leetcode

Relative Ranks

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".

pair的用法和优先队列的使用

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;
    }
};
2017/12/9 posted in  leetcode

Valid Anagram

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.length() != t.length()) return false;
        unordered_map<char, int> map;
        for (int i =0; i<s.length(); i++) {
            map[s[i]]++;
            map[t[i]]--;
        }
        for(auto s:map){
            if(s.second<0) return 0;
        }
        return 1;
    }
};
2017/12/9 posted in  leetcode

Assign Cookies

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int logG=0;
        for (int i=0; i<s.size(); i++) {
            if (g[logG]<=s[i]&&logG<g.size()) {
                logG++;
            }
        }
        return logG;
    }
};
2017/12/9 posted in  leetcode

Ransom Note

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char, int> map;
        for (int i = 0; i<magazine.length(); i++) {
            map[magazine[i]]++;
        }
        for (int j = 0; j<ransomNote.length(); j++) {
            if(--map[ransomNote[j]]<0) return 0;
        }
        return 1;
    }
};
2017/12/9 posted in  leetcode

Reverse String II

运用内置的reverse函数

class Solution {
public:
    string reverseStr(string s, int k) {
        for (int i = 0; i<s.length(); i+=2*k) {
            reverse(s.begin()+i, min(s.begin()+i+k, s.end()));
        }
        return s;
    }
};
2017/12/9 posted in  leetcode