您当前的位置: 首页 > 

IT之一小佬

暂无认证

  • 2浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

最长无重复子数组

IT之一小佬 发布时间:2021-08-31 19:04:20 ,浏览量:2

给定一个数组arr,返回arr的最长无重复元素子数组的长度,无重复指的是所有数字都不相同。

子数组是连续的,比如[1,3,5,7,9]的子数组有[1,3],[3,5,7]等等,但是[1,3,7]不是子数组

示例1

输入

        [2,3,4,5]

输出

        4

说明

        [2,3,4,5]是最长子数组    

示例2

输入

        [2,2,3,4,3]

输出

        3

说明

        [2,3,4]是最长子数组    

示例3

输入

        [9]

输出

        1

示例4

输入

        [1,2,3,1,2,3,2,2]

输出

        3

说明

        最长子数组为[1,2,3]   

示例5

输入

        [2,2,3,4,8,99,3]

输出

        5

说明

        最长子数组为[2,3,4,8,99] 

示例代码1:

#
# 
# @param arr int整型一维数组 the array
# @return int整型
#
class Solution:
    def maxLength(self , arr ):
        # write code here
        res = []
        lenght = 0
        for i in arr:
            if i not in res:
                res.append(i)
            else:
                res = res[res.index(i)+1:] + [i] 
            if lenght < len(res):
                lenght = len(res)
        return lenght

示例代码2:

#
# 
# @param arr int整型一维数组 the array
# @return int整型
#
class Solution:
    def maxLength(self , arr ):
        # write code here
        res = []
        lenght = 0
        for i in arr:
            while i in res:
                res.pop(0)
            res.append(i)
            lenght = max(lenght, len(res))
        return lenght
关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.2663s