0哈希/数组中等 NC41 最长无重复子数组

NC41 最长无重复子数组

题目描述:

给定一个数组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]是最长子数组

双指针解法:

import java.util.*;
public class Solution {
    /**
     * 
     * @param arr int整型一维数组 the array
     * @return int整型
     */
    public int maxLength (int[] arr) {
        if(arr == null){
            return 0;
        }
        int left = 0, right = 0;
        int max = 1;//最长无重复子数组的长度
        int len = 0;//以当前数字为结尾的最长子数组的长度
        while(right != arr.length-1){
             for(int i = right; i >= left; i--){
                 if(arr[right+1] == arr[i]){
                     left = i+1;
                     break;
                 }
             }
             right++;//右边界更新
             len = right - left + 1;
             max = max > len ? max : len;
        }
        return max;
    }
}

哈希解法

import java.util.*;
public class Solution {
    public int maxLength (int[] arr) {
        if(arr.length == 0){
            return 0;
        }
        Map<Integer,Integer> map = new HashMap<>();
        int left = 0, right = 0;
        int temp = 1, max = 0;
        while(right != arr.length){
            if(map.keySet().contains(arr[right])){
                left = Math.max(left,map.get(arr[right])+1);//map.get(arr[right])+1)不一定比当前的left更大,所以需要比较取更靠右的值。
            }
            map.put(arr[right],right);
            temp = right - left + 1;
            right++;
            max = max > temp ? max : temp;
        }
        return max;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值