Leetcode 128. Longest Consecutive Sequence

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.

題意:給出一個(gè)無(wú)序數(shù)組,求這個(gè)無(wú)序數(shù)組中最大的連續(xù)數(shù)組長(zhǎng)度,要求時(shí)間復(fù)雜度是O(n)。

思路:自己沒(méi)有想到解題思路,參考的是http://www.cnblogs.com/grandyang/p/4276225.html給出的解法。用set標(biāo)記全部元素,然后遍歷數(shù)組,找每個(gè)元素的最左和最右,找的部分都從set中移除,然后求左右邊界差值,更新最大長(zhǎng)度。

public int longestConsecutive(int[] nums) {
    int res = 0;
    if (nums == null || nums.length == 0) {
        return res;
    }

    HashSet<Integer> set = new HashSet<>();
    for (int num : nums) {
        set.add(num);
    }
    for (int num : nums) {
        if (set.remove(num)) {
            int left = num - 1;
            while (set.remove(left)) {
                left--;
            }
            int right = num + 1;
            while (set.remove(right)) {
                right++;
            }
            res = Math.max(res, right - left - 1);
        }
    }

    return res;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容