LeetCode Longest Consecutive Sequence

來源:互聯網
上載者:User

標籤:style   blog   color   使用   os   for   

class Solution {public:    int longestConsecutive(vector<int> &num) {        int len = num.size();                int max_cons = 0;        int cur_cons = 0;                unordered_map<int, int> sgn;        unordered_map<int, int>::iterator iter;        for (int i=0; i<len; i++) {            sgn.insert(make_pair(num[i], 0x1));        }                for (int i=0; i<len; i++) {            iter = sgn.find(num[i]);            if (iter == sgn.end()) continue; // illegal case, should not hit            if (iter->second == 0) continue; // this range has been scaned            iter->second = 0;            cur_cons = 1;                        int try_n = num[i];            // search towards negative            while (try_n != INT_MIN) {                try_n--;                iter = sgn.find(try_n);                if (iter == sgn.end()) break;                iter->second = 0;                cur_cons++;            }            try_n = num[i];            // search towards positive            while (try_n != INT_MAX) {                try_n++;                iter = sgn.find(try_n);                if (iter == sgn.end()) break;                iter->second = 0;                cur_cons++;            }            if (cur_cons > max_cons) max_cons = cur_cons;        }                return max_cons;    }};

最直觀的方法肯定是排序一下,然後從前到後掃描一遍即可,不過排序要nlogn時間,要在O(n)時間內完成的話,肯定不是基於比較排序了。可以使用桶排序,但是int的範圍還是很大的,不可取。最後採用稀疏的表示方式,就是放入hash表中,第一次遍曆數組插入以元素為key,1為value的hash表項,第二次遍曆時嘗試對每個元素的前驅後繼值在hash表中進行一次尋找,如果存在就繼續向前或向後尋找,更新連續計數cur_cons,同時將掃描到的連續hash表項的value值置零以表示該項已經進行了掃描,這樣可以避免重複資料偵測。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.