成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

[LintCode/LeetCode] Longest Consecutive Sequence

buildupchao / 956人閱讀

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

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[]數(shù)組記錄每一位上連續(xù)序列的長度,每次循環(huán)更新最大值存為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;
    }
}

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/66203.html

相關(guān)文章

  • 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

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

    xi4oh4o 評論0 收藏0
  • [Leetcode] Longest Consecutive Sequence 最長連續(xù)數(shù)列

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

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

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

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

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

    svtter 評論0 收藏0

發(fā)表評論

0條評論

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