Khi làm bài trong codesignal thì e gặp phải bài này
Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.
Example
For a = [2, 1, 3, 5, 3, 2], the output should be
firstDuplicate(a) = 3.
For a = [2, 4, 3, 5, 1], the output should be
firstDuplicate(a) = -1.
[execution time limit] 0.5 seconds (cpp)
[input] array.integer a
Guaranteed constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.
[output] integer
The element in a that occurs in the array more than once and has the minimal index for its second occurrence. If there are no such elements, return -1.
Và đây là hàm của e, ý tưởng là dùng hai vòng lặp test hết các phần tử trong mảng để tìm chỉ số giống nhau
int firstDuplicate(std::vector<int> a)
{
int length = a.size(), duplicate = -1; \\duplicate là giá trị của phần tử lặp lại
for (int i = 0; i<length; i++)
{
for (int j = i + 1; j<length; j++) //dùng hai vòng lặp để test tất cả phần tử
{
if (a[i] == a[j] && j<length) //length ở đây là chỉ số của phần tử lặp lai thứ hai
{
duplicate = a[i]; \\
length = j;
break;
}
}
}
return duplicate;
}
Hàm ban đầu của e ổn nhưng đến test thứ 21 lại quá thời gian nên e thử làm theo hướng khác.
Ý tưởng là khi gặp hai phần tử giống nhau thì bỏ vòng lặp cũ dùng vòng mới test các số giữa hai phần tử đó rồi cứ lặp lại như thế đến khi . Nhưng phần đệ quy thì e hơi yếu nên viết ra hàm ra kq sai
int truedup(std::vector<int> a, int i,int length,int duplicate)
{
if (i<length)
{
for (i;i<length;i++)
{
int j=i+1,templength=length;
for (j;j<length;j++)
{
if (a[i]==a[j] && j<length)
{
duplicate=a[i];
templength=j;
break;
}
}
if (templength<length) { length=templength; break; }
}
truedup(a,i,length,duplicate);
}
return duplicate;
}
int firstDuplicate(std::vector<int> a)
{
return truedup(a,0,a.size(),-1);
}
//Chương trình hơi xấu (nhiều phần làm đại k hiểu gì) nên nếu khó hiểu nên mọi người thông cảm.
Em muốn biết e sai chỗ nào, hoặc nếu cả chương trình e không đúng thì cho tham khảo ý tưởng. E xin cảm ơn