解题思路:
1. 边界条件1,数组长度为1,输出1
边界条件2,数组不重复,输出数组长度
2. 双指针,起始指针start_i, 和结尾指针end_i,
arr[start_i: end_i] 保证不重复
且 arr[start_i: end_i+1] 重复
3. 更新的双指针,找出最大长度
class Solution: def _find_end_idx(self, arr, start_i, end_i, curr_i): """找到终点""" end_idx = -1 tmp_set = set(arr[start_i: curr_i+1]) for i in range(curr_i+1, end_i+1): if arr[i] in tmp_set: end_idx = i break tmp_set.add(arr[i]) if end_idx == -1: return end_i return end_idx def _find_start_idx(self, arr, start_i, end_i, curr_num): """找到起始点""" for i in range(start_i, end_i): if curr_num == arr[i]: return i + 1 def maxLength(self , arr ): # write code here # 边界,长度为1 if len(arr) == 1: return 1 # 边界,均无重复 if len(arr) == len(set(arr)): return len(arr) # 双指针 # 1. 找到第一个非重复的数组终点 end_idx, start_idx, max_len = -1, 0, -1 tmp_set = {arr[0]} for i in range(1, len(arr)): if arr[i] in tmp_set: end_idx = i max_len = i break tmp_set.add(arr[i]) # 2. 开始循环执行,找到起点,更新长度, 找终点 while True: if end_idx == len(arr) - 1: break start_idx = self._find_start_idx(arr, start_idx, end_idx, arr[end_idx]) if start_idx > len(arr) - 1: break max_len = max(max_len, end_idx - start_idx + 1) end_idx = self._find_end_idx(arr, start_idx, len(arr) - 1, end_idx) max_len = max(max_len, end_idx - start_idx) return max_len