Skip to content

Commit

Permalink
Update 04.03.md
Browse files Browse the repository at this point in the history
  • Loading branch information
julycoding committed Oct 6, 2014
1 parent 64175f7 commit 58d3d7f
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions ebook/zh/04.03.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,24 +54,26 @@ Hash表需要O(n)的空间开销,且要设计hash函数,还有没有更好
开始时,保存candidate是数字0,nTimes为1;遍历到数字1后,与数字0不同,则nTimes减1变为零;接下来,遍历到数字2,2与1不同,candidate保存数字2,且nTimes重新设为1;继续遍历到第4个数字1时,与2不同,nTimes减1为零,同时candidate保存为1;最终遍历到最后一个数字还是1,与我们之前candidate保存的数字1相同,nTimes加1为1。最后返回的是之前保存的candidate为1。

思路清楚了,完整的代码如下:

```c
//a代表数组,length代表数组长度
int FindOneNumber(int* a, int length)
{
int candidate = a[0];
int nTimes, i;
for (i = nTimes = 0; i < length; i++)
int nTimes = 1;
for (int i = 1; i < length; i++)
{
if (candidate == a[i])
nTimes++;
else
nTimes--;
if (nTimes == 0)
{
candidate = a[i];
nTimes = 1;
}
else
{
if (candidate == a[i])
nTimes++;
else
nTimes--;
}
}
return candidate;
}
Expand Down

0 comments on commit 58d3d7f

Please sign in to comment.