国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LintCode/LeetCode] Longest Consecutive Sequence

buildupchao / 921人閱讀

摘要:先排序,然后用數組記錄每一位上連續序列的長度,每次循環更新最大值存為。

Problem

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

Clarification

Your algorithm should run in O(n) complexity.

Example

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

Note

先排序,然后用count[]數組記錄每一位上連續序列的長度,每次循環更新最大值存為max

Solution
public class Solution {
    public int longestConsecutive(int[] num) {
        Arrays.sort(num);
        int[] count = new int[num.length];
        count[0] = 1;
        int max = 1;
        for (int i = 1; i < num.length; i++) {
            if (num[i] == num[i-1]) count[i] = count[i-1];
            else if (num[i] == num[i-1]+1) count[i] = count[i-1]+1;
            else count[i] = 1;
            max = Math.max(max, count[i]);
        }
        return max;
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/66203.html

相關文章

  • 298. Binary Tree Longest Consecutive Sequence

    摘要:題目解答分治,一種不帶返回值,但需要用全局變量,一種帶返回值,不用全局變量有全局變量 題目:Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to a...

    荊兆峰 評論0 收藏0
  • [Leetcode] Binary Tree Longest Consecutive Sequenc

    摘要:遞歸法復雜度時間空間思路因為要找最長的連續路徑,我們在遍歷樹的時候需要兩個信息,一是目前連起來的路徑有多長,二是目前路徑的上一個節點的值。代碼判斷當前是否連續返回當前長度,左子樹長度,和右子樹長度中較大的那個 Binary Tree Longest Consecutive Sequence Given a binary tree, find the length of the lon...

    xi4oh4o 評論0 收藏0
  • [Leetcode] Longest Consecutive Sequence 最長連續數列

    摘要:集合法復雜度時間空間思路將所有數都加入集合中,然后再遍歷這些數,因為我們能的判斷某個數是否在集合中,所以我們可以一個個向上或者向下檢查。時間復雜度仍是,因為我們不會檢查不存在于數組的數,而存在于數組的數也只會檢查一次。 Longest Consecutive Sequence Given an unsorted array of integers, find the length o...

    lei___ 評論0 收藏0
  • 128. Longest Consecutive Sequence-從數組中尋找最長的連續數字

    摘要:描述例子要求分析從未排序的數組中尋找最長的連續的數字,必然要循環一遍所有的數字,因為連續,所以以出來的數字為基準,向左右擴散,直到沒有連續的,利用了和的特性。 描述: Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 例子: Given ...

    Pandaaa 評論0 收藏0
  • Binary Tree Longest Consecutive Sequence

    摘要:題目鏈接這一個類型的題都一樣用,分治的思想。兩種方式一種用,另一種直接把的長度作為返回值,思路都一樣。也可以解,用或者來做,但是本質都是。用用返回值在當前層處理分別處理左右節點,這樣不用傳上一次的值,注意這樣初始的就是了 Binary Tree Longest Consecutive Sequence 題目鏈接:https://leetcode.com/problems... 這一個類...

    svtter 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<