longest consecutive sequence

来源:互联网 发布:无线网络转换有线网络 编辑:程序博客网 时间:2024/05/21 01:42


solution

class Solution {public:    int longestConsecutive(vector<int>& nums) {        unordered_set<int> st;        for( auto n : nums ) { st.insert(n);}                 int rst = 0;        for( int n : nums) {            int left = n - 1;            while( st.find(left) != st.end() ) {                st.erase(left);                left--;            }                        int right = n + 1;            while(st.find(right) != st.end() ) {                 st.erase(right);                right++;            }            rst = max(rst, right - left - 1);        }        return rst;    }};

想法很奇妙 , 但是我没想到union find 怎么解

0 0
原创粉丝点击