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

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

牛客网:NC41 最长无重复子数组

官方示例

示例1

输入

[2,3,4,5]

输出

4
示例2

输入

[2,2,3,4,3]

输出

3
示例3

输入

[9]

输出

1
示例4

输入

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

输出

5
实例6

输入

[1, 2, 3, 4, 4, 3, 3, 1, 2, 3, 4, 3, 1, 7, 6, 2, 1]

输出

6

说明:其中最长重复元素为[4, 3, 1, 7, 6, 2]

解题思路

这道题使用两个指针来实现,其中,左指针start和右指针end为0,开始时,做执政第一个数半段hash表里面是否有重复的值,没有将数字加入,以此类推。若存在,此时记录下表的长度,然后从右边开始移除start指向的元素,start自增,一直到待加入元素不为重复为止,这样就可以找出无重复的子数组列表长度了。

代码实现

public int maxLength(int[] arr) {
    int res = 0;
    int start = 0;
    int end = 0;
    Map<Integer, Integer> map = new HashMap<>();
    while (end < arr.length) {
       	// 若不存在,添加元素
        if (!map.containsKey(arr[end])) {
            map.put(arr[end], 1);
            end++;
        } else {
            // 首先获取列表长度,然后用res保留最大值
            if (res < end - start) {
                res = end - start;
            }
            //移除待添加元素直到没有重复元素为止
            while (map.containsKey(arr[end])) {
                map.remove(arr[start]);
                start++;
            }
        }
    }
    return Math.max(res, end - start);
}

相关文章:

  • 2021-05-18
  • 2021-06-04
  • 2022-12-23
  • 2021-08-25
  • 2022-02-08
  • 2022-12-23
  • 2021-10-06
猜你喜欢
  • 2022-02-15
  • 2022-12-23
  • 2021-11-09
  • 2021-12-08
  • 2021-07-31
  • 2021-12-29
  • 2021-06-16
相关资源
相似解决方案