Leetcode-992 Subarrays with K Different Integers(K 个不同整数的子数组)

 1 #define maxn 1000000
 2 #define _for(i,a,b) for(int i = (a);i < (b);i ++)
 3 #define pb push_back
 4 
 5 class Solution
 6 {
 7     public:
 8         vector<int> root;
 9         int _find(int x)
10         {
11             if(root[x]==x)    return x;
12             return root[x] = _find(root[x]);
13         }
14         void merge(int x,int y)
15         {
16             int rx = _find(x);
17             int ry = _find(y);
18             if(rx==ry) return ;
19             root[rx] = ry;
20         }
21         bool equationsPossible(vector<string>& equations)
22         {
23             for(int i = 0;i < 27;i ++)
24                 root.pb(i);
25 
26             for(int i = 0; i < equations.size(); i ++)
27             {
28                 if(equations[i][1]=='=')
29                 {
30                     merge(equations[i][0]-'a',equations[i][3]-'a');
31                 }
32             }
33             for(int i = 0; i < equations.size(); i ++)
34             {
35                 if(equations[i][1]=='!')
36                 {
37                     if(_find(equations[i][0]-'a')==_find(equations[i][3]-'a'))
38                         return false;
39                 }
40             }
41             return true;
42         }
43 };

并查集水过

上一篇:LC 992. Subarrays with K Different Integers


下一篇:[Swift Weekly Contest 123]LeetCode992. K 个不同整数的子数组 | Subarrays with K Different Integers