LeetCode 136:Single Number

来源:互联网 发布:淘宝网创立时间 编辑:程序博客网 时间:2024/06/07 00:55

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 ans=0;        for(int i=0;i<nums.size();i++)            ans^=nums[i];        return ans;    }};


0 0