摘要:先排序,然后用數(shù)組記錄每一位上連續(xù)序列的長度,每次循環(huán)更新最大值存為。
Problem
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
ClarificationYour algorithm should run in O(n) complexity.
ExampleGiven [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
先排序,然后用count[]數(shù)組記錄每一位上連續(xù)序列的長度,每次循環(huán)更新最大值存為max。
Solutionpublic 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
摘要:題目解答分治,一種不帶返回值,但需要用全局變量,一種帶返回值,不用全局變量有全局變量 題目: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...
摘要:遞歸法復(fù)雜度時間空間思路因為要找最長的連續(xù)路徑,我們在遍歷樹的時候需要兩個信息,一是目前連起來的路徑有多長,二是目前路徑的上一個節(jié)點的值。代碼判斷當(dāng)前是否連續(xù)返回當(dāng)前長度,左子樹長度,和右子樹長度中較大的那個 Binary Tree Longest Consecutive Sequence Given a binary tree, find the length of the lon...
摘要:集合法復(fù)雜度時間空間思路將所有數(shù)都加入集合中,然后再遍歷這些數(shù),因為我們能的判斷某個數(shù)是否在集合中,所以我們可以一個個向上或者向下檢查。時間復(fù)雜度仍是,因為我們不會檢查不存在于數(shù)組的數(shù),而存在于數(shù)組的數(shù)也只會檢查一次。 Longest Consecutive Sequence Given an unsorted array of integers, find the length o...
摘要:描述例子要求分析從未排序的數(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 ...
摘要:題目鏈接這一個類型的題都一樣用,分治的思想。兩種方式一種用,另一種直接把的長度作為返回值,思路都一樣。也可以解,用或者來做,但是本質(zhì)都是。用用返回值在當(dāng)前層處理分別處理左右節(jié)點,這樣不用傳上一次的值,注意這樣初始的就是了 Binary Tree Longest Consecutive Sequence 題目鏈接:https://leetcode.com/problems... 這一個類...
閱讀 1335·2021-11-15 11:37
閱讀 3519·2021-11-11 16:55
閱讀 1778·2021-08-25 09:39
閱讀 3241·2019-08-30 15:44
閱讀 1754·2019-08-29 12:52
閱讀 1429·2019-08-29 11:10
閱讀 3262·2019-08-26 11:32
閱讀 3252·2019-08-26 10:16