https://www.nowcoder.com/practice/b56799ebfd684fb394bd315e89324fb4?tpId=188&&tqId=36856&rp=1&ru=/ta/job-code-high-week&qru=/ta/job-code-high-week/question-ranking
题目描述
给定一个数组arr,返回arr的最长无的重复子串的长度(无重复指的是所有数字都不相同)。
示例1
输入
[2,3,4,5]
返回值
4
示例2
输入
[2,2,3,4,3]
返回值
3
最基本的思路,比较简单。
import java.util.*;
public class Solution {
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength (int[] arr) {
// write code here
// 存储当前无重复的数字
HashSet<Integer> set = new HashSet<>();
// end 表示尾端指针
int end = 0;
// start 表示首端指针
int start = 0;
// 当前最大长度
int max = 0;
while(end < arr.length && start < arr.length){
if(!set.contains(arr[end])){
set.add(arr[end]);
end++;
} else{
max = Math.max(max,set.size());
start = findRepeat(arr,start,end) + 1;
end = start;
set.clear();
}
}
return Math.max(max,set.size());
}
private int findRepeat(int[] arr, int start, int end){
int target = arr[end];
for(int i = start; start < end; i++){
if(arr[i] == target){
return i;
}
}
return end;
}
}
同样使用双指针,换一个写法,
public int maxLength (int[] arr) {
// write code here
// 存储当前无重复的数字
HashSet<Integer> set = new HashSet<>();
// end 表示尾端指针
int end = 0;
// start 表示首端指针
int start = 0;
// 当前最大长度
int max = 0;
while(end < arr.length && start < arr.length){
if(!set.contains(arr[end])){
set.add(arr[end]);
end++;
} else{
max = Math.max(max,set.size());
set.remove(arr[start]);
start++;
}
}
return Math.max(max,set.size());
}
空间换时间,用hash表存储元素和对应下标位置,减少遍历的时间
public int maxLength (int[] arr) {
// write code here
// 存储当前无重复的数字,key为数组,value为下标
HashMap<Integer,Integer> map = new HashMap<>();
// end 表示尾端指针
int end = 0;
// 当前最大长度
int max = 0;
while(end < arr.length){
if(!map.containsKey(arr[end])){
map.put(arr[end],end);
end++;
} else{
max = Math.max(max,map.size());
end = map.get(arr[end]) + 1;
map.clear();
}
}
return Math.max(max,map.size());
}