码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Single Number (Medium) ☆

时间:2014-11-20 14:59:10      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   strong   

题目:

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?

 

要求O(n)算法,还不能有辅助空间。开始用了各种O(n^2)的方法,都超时,后来突然顿悟了。异或可以消掉两个相同数字。

直接把所有数字异或在一起,就是单独的那个数字了。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public://异或可以把两个相同的数字消除 O(n) AC
    int singleNumber3(int A[], int n) {
        int ans = 0;
        for(int i = 0; i < n; i++)
        {
            ans ^= A[i];
        }
        return ans;
    }
};

int main()
{
    Solution s;
    int a[9] = {0,0,1,1,2,3,2,3,4};
    int n = s.singleNumber3(a, 9);

    return 0;
}

 

【leetcode】Single Number (Medium) ☆

标签:style   blog   io   ar   color   os   sp   for   strong   

原文地址:http://www.cnblogs.com/dplearning/p/4110566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!