[LeetCode] Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

前几天一个哥们强烈推荐了这个LeetCode OJ 试了几道题,觉得这个网站真的屌炸天。决定把这些题目都做一下,尽量做完。实在不会的就借鉴别人的结题报告好了。

思路:简单的异或操作即可。

class Solution {
public:
    int singleNumber(int A[], int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int single = 0;
        for( int i = 0; i < n; i++ ) {
            single ^= A[i];
        }
        return single;
    }
};

原题:http://oj.leetcode.com/problems/single-number/

posted on 2013-10-19 23:19  風逍遥  阅读(144)  评论(0编辑  收藏  举报

导航