最长连续序列(java)_128

最长连续序列(java)_128_第1张图片

package cn.tulingxueyuan.hashTable;

import java.util.HashSet;
import java.util.Set;

/**
 * Author: sl
 * date:   2022/11/1
 * time:   9:59 下午
 */
public class longestConsecutiveSequence_128 {
    public static void main(String[] args) {
        int[] nums = new int[]{100, 4, 200, 1, 3, 2};
        System.out.println(new longestConsecutiveSequence_128().longestConsecutive(nums));
    }

    public int longestConsecutive(int[] nums) {
        // 定义一个哈希表
        Set<Integer> nums_set = new HashSet<>();
        for (int num : nums) {
            nums_set.add(num);
        }
        int longestStreak = 0;
        // 开始循环
        for (int num : nums_set) {
            if (!nums_set.contains(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;
                while (nums_set.contains(currentNum + 1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }
                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }
        return longestStreak;
    }
}


from typing import List

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        # 定义变量
        longest_streak = 0
        nums_set = set(nums)
        # 开始遍历
        for num in nums_set:
            if num - 1 not in nums_set:
                current_num = num
                current_streak = 1
                while current_num + 1 in nums_set:
                    current_num += 1
                    current_streak += 1

                longest_streak = max(longest_streak,current_streak)

        return longest_streak

if __name__ == "__main__":
    solution = Solution()
    list = [100, 4, 200, 1, 3, 2]
    print(solution.longestConsecutive(list))

你可能感兴趣的:(算法,算法)