2103. 环和杆

我的解法:

其中使用了std::find迭代器

class Solution {
public:
    int countPoints(string rings) {
        vector<vector<int>> v(10);
        for(int i=0; i<rings.size(); i++){
            char letter;
            if (i%2==0) {
                letter = rings[i];
                continue;
            }
            int num = rings[i]-'0';
            if(std::find(v[num].begin(), v[num].end(), letter) == v[num].end()){
                v[num].push_back(letter);
            }
        }
        int ans=0;
        for(int i=0; i<10; i++){
            if(v[i].size()==3) ans++;
        }
        return ans;
    }
};

使用位运算进行求解

将原来的10x3的状态维护压缩为10个3位二进制数的维护

class Solution {
public:
    static constexpr int POLE_NUM = 10;
    int countPoints(string rings) {
        vector<int> state(POLE_NUM);
        for(int i=0; i<rings.size(); i+=2){
            char color = rings[i];
            if(color=='R'){
                state[rings[i+1]-'0'] |=1;
            }else if(color=='G'){
                state[rings[i+1]-'0'] |=2;
            }else{
                state[rings[i+1]-'0'] |=4;
            }
        }
        int ans=0;
        for(int i=0; i<POLE_NUM; i++){
            if(state[i]==7) ans++;
        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode,算法,数据结构,c++)