帮助

内容读取中…

内容读取中…

首页  |  相册  |  共享  |  群组
搜索

正文

Find the number with odd number of occurrences, within O(n) time and O(1) additional space (2009-09-16 14:53)

Problem: You are given an array of n integers.  All the integers occur even number of times except one. Find this integer with O(n) time and O(1) additional space.

Solution: Due to the time and space required, it's not possible to finish this job by counting the number of occurrences for each integer of the array. An intuition that it's the combination of scan (O(n) time required) and some kind of arithmetic operator. XOR, yes, Exclusive OR, that's the operator I want! For integers A, B and C, A XOR B XOR C == B iff A == C.

OK, here comes my solution (C++ style):

/*-

- theArray          array for the integers

- n                       length of the array

-*/

int GetSpecialOne(int *theArray, int n)

{

    assert(n > 0);

    int nSpecialOne = theArray[n - 1];

    for (int i = n - 2; i >= 0; i --) {

        nSpecial ^= theArray[i];

    }

    return nSpecial;

}

 

评论 (0) | 阅读 (6)

评论
    内容读取中…
发表评论

你还没有登录,现在登录

个人档案

内容读取中…

博客公告

内容读取中…

博客日历

内容读取中…

文章分类

内容读取中…

文章存档

    内容读取中…

最新发表

    内容读取中…

最新评论

内容读取中…

给博主留言

内容读取中…

博主好友

内容读取中…

最新访客

内容读取中…

博客统计

    内容读取中…

友情链接

新闻订阅