题目
给定一个长度为n的数组arr,返回arr的最长无重复元素子数组的长度,无重复指的是所有数字都不相同。子数组是连续的,比如[1,3,5,7,9]的子数组有[1,3],[3,5,7]等等,但是[1,3,7]不是子数组
数据范围:
0≤arr.length≤10
0<arr[i]≤10
要求:空间复杂度 O(n),时间复杂度 (nlogn)
思路
双指针遍历的暴力解法肯定是超时的,所以只能遍历一遍,要求是无重复的,那么用一个storage来存储不重复的元素,当right到i位置时候找到了一个元素和storage中是重复的,那么将这个storage中的这个重复元素和它之前的元素全部踢出,再进行添加新的元素,过程中不断更新storage的长度最大值。
代码
python代码:
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param arr int整型一维数组 the array
# @return int整型
#
class Solution:
def maxLength(self , arr: List[int]) -> int:
# write code here
length = len(arr)
max_value = 0
storage = []
for i in range(length):
if arr[i] not in storage:
storage.append(arr[i])
else:
index = storage.index(arr[i])
storage = storage[index+1:]
storage.append(arr[i])
max_value = max(max_value, len(storage))
return max_value
c++代码:
class Solution {
public:
/**
*
* @param arr int整型vector the array
* @return int整型
*/
int maxLength(vector<int>& arr) {
// write code here
map<int, int> m;
int left=0; int right=0;
int ret=0;
while(right<arr.size()){
if(m[arr[right]]==0){
m[arr[right]] = right+1;
ret = max(ret, right-left+1);
}else{
for(; left<m[arr[right]]; left++){
m[arr[left]]=0;
}
m[arr[right]] = right + 1;
}
right++;
}
return ret;
};
};