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

【一天一道LeetCode】#136. Single Number

时间:2016-07-19 11:04:51      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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?

(二)解题

题目大意:一组数中除了一个数之外其他的数都出现两次,请找出这个出现一次的数
解题思路:采用异或运算很快就能找出出现一次的数。
由于异或满足交换和结合率,出现两次的数异或都为0,最后只剩下那个出现一次的数。
所以只需要遍历一次数组,一直异或就可以算出出现一次的数。

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int size = nums.size();
        if(size==0) return 0;
        int ret = 0;
        for(int i = 0 ; i< size ; i++)
        {
            ret=ret^nums[i];//数组内所有的数做异或运算
        }
        return ret;
    }
};

【一天一道LeetCode】#136. Single Number

标签:

原文地址:http://blog.csdn.net/terence1212/article/details/51934096

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