leetcode 136 Single Number bit Option

2019-08-16 07:48:42来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

leetcode 136 Single Number bit Option

Linked Url:https://leetcode.com/problems/single-number/

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 };

 


原文链接:https://www.cnblogs.com/CS-WLJ/p/11181720.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:DFS(四):剪枝策略

下一篇:luogu1368 工艺