為什麼這篇codility解答鄉民發文收入到精華區:因為在codility解答這個討論話題中,有許多相關的文章在討論,這篇最有參考價值!作者babelism (Bob)看板C_and_CPP標題[分享] Codility demo sa...
說是心得嘛... 當灌水也行XD
這是 Codility 的 demo sample,
提供一個滿分解答。
(Codility 是程設訓練平台,某些公司會用這個平台來面試)
====================
This is a demo task.
Write a function:
int solution(vector<int> &A);
that, given an array A of N integers, returns the smallest positive integer
(greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [-1, -3], the function should return 1.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range
[-1,000,000..1,000,000]
給分的重點在於運算速度要快、對於上下限的處理要明確、
Compile 連 warning 都不能。時間複雜度在 O(N^2) 以上的都不及格。
限時30分鐘。
==================== 範例碼在下面 ====================
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
if (A.size() > 100000)
{
return 100001;
}
if (A.empty())
{
return 1;
}
bool ba[A.size()] = {false};
for (unsigned int ix = 0; ix < A.size(); ix++)
{
if (A[ix] < 1)
{
continue;
} else
{
if ((unsigned int)A[ix] > A.size())
{
continue;
}
}
ba[A[ix]-1] = true;
}
for (unsigned int ix = 0; ix < A.size(); ix++)
{
if (ba[ix] == false)
{
return ix+1;
}
}
return A.size() + 1;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 27.147.15.203
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1535983690.A.ED1.html
如果對 STL 熟悉的話,可以這樣寫,不用開 array,也是滿分解法
int solution(vector<int> &A) {
int result = 1;
bool found = false;
sort(A.begin(), A.end());
do
{
found = binary_search(A.begin(), A.end(), result);
if (found)
{
result++;
}
} while (found);
return result;
}
不過我個人不太喜歡這解法。