【leetcode】Longest Consecutive Sequence

來源:互聯網
上載者:User

Question :  

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

Anwser 1 :   

class Solution {public:    int longestConsecutive(vector<int> &num) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        map<int, int> hmap;        hmap.clear();        int n = num.size();        for(int i=0; i<n; i++){            //hmap.insert(pair<int, int>(num[i], i));            hmap[num[i]] = i;        }        int ans=0, cnt=0;        map<int, int>::iterator it;        for(int i=0; i<n; i++)        {            int cur = num[i];            it = hmap.find(num[i]);     // value            cnt++;            if(it!=hmap.end())            {                map<int, int>::iterator iter;                while(1){                    iter = hmap.find(++cur);    // to larger value                    if(iter == hmap.end())                        break;                    cnt++;                        hmap.erase(iter);                }                cur=num[i];                while(1){                    iter = hmap.find(--cur);    // to smaller value                    if(iter == hmap.end())                        break;                    cnt++;                        hmap.erase(iter);                }                ans = cnt > ans ? cnt : ans;            }            cnt=0;      // init to count remaider value of hmap        }        return ans;    }};

注意點:

1) 採用map,value為map_key, index為map_value

2) 按value++, value--尋找,找到了則從map移除(erase),減少for迴圈find的次數

3) for + while,時間複雜度最壞其實為O(n*n),但是仍然編譯通過了...

Anwser 2 :   

class Solution {public:    int getCount(map<int, int> &hmap, int value, bool asc){        int count = 0;                while(hmap.find(value) != hmap.end()){            hmap.erase(value);            count++;                        if(asc){                value++;            } else {                value--;            }        }        return count;    }    int longestConsecutive(vector<int> &num) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        map<int, int> hmap;        hmap.clear();        int n = num.size();        for(int i=0; i<n; i++){            //hmap.insert(pair<int, int>(num[i], i));            hmap[num[i]] = i;        }        int ans=0, cnt=0;        for(int i=0; i<n; i++)        {            int count = getCount(hmap, num[i], false) + getCount(hmap, num[i]+1, true);            ans = count > ans ? count : ans;        }        return ans;    }};

注意點:

1) 改進了方法1

2) getCount()找到則移除,count++,繼續尋找下一個

3) count = getCount(hmap, num[i], false) + getCount(hmap, num[i]+1, true);  注意暗紅色部分,加1為因為之前num[i]已經被移除了,因此找其上面一個value + 1

Anwser 3 : 

class Solution {public:    int longestConsecutive(vector<int> &num) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        map<int, int> hmap;        hmap.clear();        int n = num.size();        for(int i=0; i<n; i++){            hmap.insert(pair<int, int>(num[i], 1));     // map will auto sort by key(num[i])            //hmap[num[i]] = 1;        }        int ans = 1;        // min init        int pre_k = 0;        int pre_v = 0;                map<int, int>::iterator it;        for(it = hmap.begin(); it != hmap.end(); it++)        {            if(it == hmap.begin()) {                pre_k = it->first;                pre_v = it->second;                continue;            }                        if(it->first == pre_k + 1){                it->second = pre_v + 1;                ans = it->second > ans ? it->second : ans;            }            pre_k = it->first;            pre_v = it->second;                    }        return ans;    }};

注意點:

1) 方法2的進一步改進

2) 此方法最大的利用了map自動根據key(num[i])排序,且value設為了1(起始值)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.