题解 | #最长无重复子数组#
最长无重复子数组
https://www.nowcoder.com/practice/b56799ebfd684fb394bd315e89324fb4
class Solution {
public:
/**
*
* @param arr int整型vector the array
* @return int整型
*/
int maxLength(vector<int>& arr) {
// write code here
unordered_set<int> hash;
int res = 0;
for (int i = 0, j = 0; i < arr.size(); i++) {
while (hash.count(arr[i])) {
hash.erase(arr[j]);
j++;
}
hash.insert(arr[i]);
res = max(res, i - j + 1);
}
return res;
}
};
- 思路:哈希表+滑动窗口
- 哈希表维护滑动窗口中出现的数字,遍历整个数组,每当新加入的数字在滑动窗口中出现过时,收缩左边界,直到该数字不出现,记录最长窗口长度
- 时间复杂度:O(n)
- 空间复杂度:O(n)

