当前位置: 移动技术网 > IT编程>开发语言>C/C++ > leetcode 136 Single Number bit Option

leetcode 136 Single Number bit Option

2019年07月15日  | 移动技术网IT编程  | 我要评论

帝赐尔,3158con,皇朝足球吧

linked url:

given a non-empty 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?

example 1:
input: [2,2,1] output: 1
example 2:
input: [4,1,2,1,2] output: 4

solution:

the method is xor option, principles is  : 0 xor 0 = 0; 0 xor 1 = 1;any  num xor itself  =  0,so we pass the array and xor its elements all,so the result  which is we want.

ac code follow: 

1 class solution {
2 public:
3     int singlenumber(vector<int>& nums) {
4         int res = nums[0];
5         for(int i = 1;i < nums.size();++i)
6             res = nums[i]^res;
7         return res;
8     }
9 };

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网