【leetcode】136. Single Number

来源:互联网 发布:尺度最大的网络女主播 编辑:程序博客网 时间:2024/06/17 00:04

一、题目描述

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?


题目解读:给一个整数数组,数组中只有一个数只出现过一次,其他的数都出现过2次。找出这个只出现一次的数。


思路:两个相同的数异或得0,因此可以将数组所有的数都进行异或运算,最后得到的数一定是只出现一次的数。


c++代码(20ms,28.40%)

class Solution {public:    int singleNumber(vector<int>& nums) {        int result=0;        for(int i=0; i<nums.size(); i++)            result ^= nums[i];        return result;    }};


总结:

位运算:& (按位与), | (按位或), ^ (按位异或), ~ (按位取反)


0 0