日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

[LeetCode] Longest Consecutive Sequence 求解

發布時間:2025/3/8 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LeetCode] Longest Consecutive Sequence 求解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

為什么80%的碼農都做不了架構師?>>> ??

題目

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.

思路

  • (預處理)保存一個哈希表(或者集合),用于o(1)時間查找該數字是否存在于數組當中

  • 數字有可能重復,所以其實哈希集合就夠了,典型的空間換時間

  • (預處理)一個表征是否使用的used表,用于o(1)時間查找該數字是否已經被包含在另外一個序列當中

  • 注意數字有可能是負數,所以直接用數組不好

  • 輪詢數組,遇到一個數字,查找其左,右的最長連續序列長度,并記錄與已知最大長度相比較

代碼

public class Solution {public int longestConsecutive(int[] num) {Map<Integer, Integer> map = new HashMap<Integer, Integer>();for (int i = 0; i < num.length; i++) {map.put(num[i], i);}Map<Integer, Boolean> used = new HashMap<Integer, Boolean>();for (int i : num) {used.put(i, false);}int max = Integer.MIN_VALUE;for (int i = 0; i < num.length; i++) {if (!used.get(num[i])) {used.put(num[i], true);int k = num[i];int leftLength = findLength(k, map, "left");int rightLength = findLength(k, map, "right");// mark usedfor (int j = 0; j < leftLength; j++) {used.put(k - j - 1, true);}for (int j = 0; j < rightLength; j++) {used.put(k + j + 1, true);}int total = leftLength + rightLength + 1;if (total > max) {max = total;}}}return max;}private int findLength(int k, Map<Integer, Integer> map, String direction) {if ("left".equals(direction)) {int l = k - 1;while (map.containsKey(l)) {l -= 1;}return k - l - 1;} else {int l = k + 1;while (map.containsKey(l)) {l += 1;}return l - k - 1;}} }

轉載于:https://my.oschina.net/zuoyc/blog/338719

總結

以上是生活随笔為你收集整理的[LeetCode] Longest Consecutive Sequence 求解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。