Java calculates the longest unduplicated substring length of an integer array

Title description

Given an array arr, return the length of the longest repeating substring of arr (no repeating means that all numbers are different).

Example 1

enter

[2,3,4,5]

return value

4

Example 2

enter

[2,2,3,4,3]

return value

3

Remarks:

1<n<10 to the 5th power

 

import java.util.*;


public class Solution {
    /**
     * 
     * @param arr int整型一维数组 the array
     * @return int整型
     */
    public int maxLength (int[] arr) {
        //如:[1,2,3,4,5,6,7,8,1,11,12,13,14] startIndex =0 当遍历到数组第8个位置1的时候,
        //此时应从第一次出现重复元素0的位置元素1的下一个位置[2,3,4,5,6,7,8,1,11,12,13,14]
        //开始滑动
        if(arr == null || arr.length == 0){
            return 0;
        }
        
        int startIndex = 0;
        int maxLen = 0;
        //hash数组长度为10的5次方,因为题中1≤n≤10的5次方 hash数组Index 0-99999 初始化中每个元素初始值为0
        int[] hash = new int[100000];
        int result = 0;
        
        for(int i=0;i<arr.length;i++){
            
            int currentArrayVal = arr[i];
            
            //如果没有不重复元素,hash[currentArrayVal]这个值就一直是0,那么start不会改变
            //如果出现重复元素,就会取重复元素的索引的位置的值,作为索引值
            startIndex = Math.max(startIndex,hash[currentArrayVal]);
            result = Math.max(result,i-startIndex+1);
            
            //存储当前元素的下一个元素坐标 因为涉及上面如果命中重复元素,startIndex要从之前重复元素坐标的下一位开始滑动
            //如[1,2,3,4,5,6,7,8,1,11,12,13,14] startIndex =0 第一次存储1在hash中的是 0+1=1 
            //当遍历到第二个1的时候,需要数组滑动1位计算无重复子串[1,2,3,4,5,6,7,8,1,11,12,13,14] startIndex =1 
            //算出[2,3,4,5,6,7,8,1,11,12,13,14]是最长无重复子串结果
            hash[currentArrayVal] = i + 1;
        }
        
        return result;
    }
}

 

Guess you like

Origin blog.csdn.net/luzhensmart/article/details/112757505