Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2020农行秋招题# #285

Open
MyLinChi opened this issue Aug 30, 2020 · 0 comments
Open

2020农行秋招题# #285

MyLinChi opened this issue Aug 30, 2020 · 0 comments

Comments

@MyLinChi
Copy link
Owner

问题

对一个字符串数组排序,每个字符串有两个字符,第一个是字符,第二个是数字。

求解

把这道题粘出来是因为涉及C++类中静态数组的初始化,虽然只有一行,但写少了可以纠结半天~

#include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<algorithm>
using namespace std;
class Solution {
private:
    void swap(string& a, string& b) {
        string t = a;
        a = b;
        b = t;
    }
    int randind(int s, int e) {
        return rand() % (e - s + 1) + s;
    }
    static int mp[26];
    static bool cmp(const string& a, const string& b) {
        if (a[0] == b[0]) {
            return a[1] < b[1];
        }
        else {
            return mp[a[0] - 'a'] < mp[b[0] - 'a'];
        }
    }

    int partion(vector<string>& data, int s, int e) {
        int left = s - 1;
        int right = s;
        int i = randind(s, e);
        swap(data[i],data[e]);
        for (; right < e; ++right) {
            if (cmp(data[right],data[e])) {
                swap(data[++left],data[right]);
            }
        }
        swap(data[++left], data[e]);
        return left;
    }

    void quicksort(vector<string>& data, int s, int e) {
        if (s >= e)return;
        int i = partion(data, s, e);
        quicksort(data, s, i - 1);
        quicksort(data, i + 1, e);
    }
public:
    void fun() {
        mp['e' - 'a'] = 5;
        mp['a' - 'a'] = 4;
        mp['o' - 'a'] = 3;
        mp['i' - 'a'] = 2;
        mp['u' - 'a'] = 1;
        vector<string> data = {
            "a3","a4","a5","a6",
            "e3","e4","e5","e6",
            "i3","i4","i5","i6",
            "o3","o4","o5","o6",
            "u3","u4","u5","u6",
        };
        //quicksort(data, 0, data.size() - 1);
        sort(data.begin(), data.end(), cmp);
        for (auto s : data)cout << s << endl;
    }
};
int Solution::mp[26];

int main() {
    Solution sol;
    sol.fun();
    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant