Leecode热题100---128:最长连续数列

题目:
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

1、C++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int longestConsecutive(vector<int>& nums)
{
	if (nums.size() == 0)
		return 0;
	// vector数组升序排序
	sort(nums.begin(), nums.end());
	// 初始化最长连续序列长度为1,当前连续序列长度pcnt为1
	int cnt = 1, pcnt = 1;
	for (int i = 1; i<nums.size(); i++)
	{
		if (nums[i] - nums[i - 1] == 1)
			pcnt++;
		else if (nums[i] - nums[i - 1] > 1)
		{
			if (pcnt>cnt)
				cnt = pcnt;
			pcnt = 1;
		}
	}
	// 末尾判断是否需要更新局部变量值
	return pcnt>cnt ? pcnt : cnt;
}

2、python

import cv2
import numpy as np

class Solution:
    def Longest(self,nums:List[int]) -> int:
        # 构建 set,去重,建立一个List集合,用来存放去重后的元素
        set_nums = set(nums)
        # 初始化一个最大长度变量,用于后续更新
        len_max = 0

        for num in set_nums:
            # 如果 num - 1 不在 set_nums 中,那 current num 可以作为连续子序列的首部
            if num-1 not in set_nums:
                len_seq = 1;

                # 如果 num + 1 不在 set_nums 中,那就达到了连续子序列的尾巴
                while num+1 in set_nums:  # 以 current num 进行枚举
                    len_seq +=1
                    num += 1
                # 更新最大长度变量
                len_max = max(len_max,len_seq)
        return len_max

相关推荐

  1. Leecode100---128连续数列

    2024-05-15 22:30:03       27 阅读
  2. LeetCode-100128.连续序列

    2024-05-15 22:30:03       41 阅读
  3. leetcode100.连续序列

    2024-05-15 22:30:03       41 阅读
  4. LeetCode 128.连续数列

    2024-05-15 22:30:03       41 阅读
  5. 连续序列 - LeetCode 3

    2024-05-15 22:30:03       38 阅读
  6. LeetCodeHot100 - 有效括号

    2024-05-15 22:30:03       32 阅读
  7. LeetCode每日刷.09(128.连续序列)

    2024-05-15 22:30:03       52 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-15 22:30:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-15 22:30:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-05-15 22:30:03       82 阅读
  4. Python语言-面向对象

    2024-05-15 22:30:03       91 阅读

热门阅读

  1. CSAP_MAT_BOM_MAINTAIN 返回消息处理

    2024-05-15 22:30:03       26 阅读
  2. Spring STOMP-权限

    2024-05-15 22:30:03       30 阅读
  3. Python3 笔记:continue语句和break语句的区别

    2024-05-15 22:30:03       31 阅读
  4. [ffmpeg处理指令]

    2024-05-15 22:30:03       33 阅读
  5. Excel表格导入/导出数据工具类

    2024-05-15 22:30:03       30 阅读
  6. 算法训练营第二十五天 | LeetCode 669 修剪二叉树、

    2024-05-15 22:30:03       29 阅读
  7. 电池的一些UL认证标准

    2024-05-15 22:30:03       28 阅读
  8. vue2中封装弹框插件

    2024-05-15 22:30:03       32 阅读
  9. 牛客周赛 Round 39vp(A--F)

    2024-05-15 22:30:03       36 阅读