最开始没有使用哈希表,而是直接使用一个变量存储目前子数组的头部位置来记录信息,但是这种做法虽然五个测试用例都能通过,切在提交后也能通过8个用例,但唯独第九个用例无法通过,原因目前仍未确定,尝试修改一些细节,但都无解,希望看出来的大佬可以告知我。有问题的初版代码如下:
class Solution {
public:
/**
*
* @param arr int整型vector the array
* @return int整型
*/
int maxLength(vector<int>& arr) {
// write code here
int max = 0;
int length = 0;
int head = 0;
//int rear = 0;
for(int i = 0;i < arr.size();i++){
bool ct = false;
if(head == i){
length = 1;
continue;
}
for(int j = head;j < i;j++){
if(arr.at(j) == arr.at(i)){
head = i;
if(length > max){
max = length;
}
length = 1;
ct = true;
continue;
}
}
if(ct){
continue;
}
length++;
}
if(length > max){
max = length;
}
return max;
}
}; 在对上述代码进行多次修改均无法通过第九个用例后,我参考了评论区大佬的代码,写出了下面这版能提交通过的代码。但我认为,我上面那版的代码的思路跟这版并无二致,只是上面那版在移动头指针时是直接使head=i,而下面这版是逐次移动的。观察第九个用例的输入发现其数据量极大,调试起来也很不方便,实在是无法发现原因。
class Solution {
public:
/**
*
* @param arr int整型vector the array
* @return int整型
*/
int maxLength(vector<int>& arr) {
unordered_map<int, int> heap;
int res = 0;
for (int i = 0, j = 0; i < arr.size(); ++i)
{
heap[arr[i]]++;
//while (heap[arr[i]] > 1) heap[arr[j++]]--;
while(heap[arr[i]] > 1){
heap[arr[j]]--;
j++;
}
res = max(res, i - j + 1);
}
return res;
}
}; 
京公网安备 11010502036488号