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

Leetcode:Singel Number

时间:2014-10-24 13:08:49      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:leetcode   algorithm   

问题描述:

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?

解题思路:本题可以用位运算来求解。因为a^0=a,a^a=0,a^b=b^a(即异或运算满足交换律),且已知数组中除了要找的元素,每个元素都出现两次。则可以将数组中的各元素依次异或。根据异或运算的交换律,可以改变运算顺序使出现两次的元素相邻,则所有出现两次元素异或的结果为0。最后得到异或的结果为要找的元素。

代码:

class Solution {
public:
    int singleNumber(int A[], int n) {
        int i;
        int result = A[0];
        for(i = 1;i < n;i++)
            result = result ^ A[i];
        return result;
    }
};


Leetcode:Singel Number

标签:leetcode   algorithm   

原文地址:http://blog.csdn.net/yao_wust/article/details/40424119

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