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

[Algorithm] 136. Single Number

时间:2019-12-04 20:07:35      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:output   let   ref   tor   bit   app   exce   col   java   

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

 

var singleNumber = function(nums) {
    let res = 0;
    for (let i = 0; i < nums.length; i++) {
        res = res ^ nums[i]
    }
    return res;
};

 

It uses XOR: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR

For example, 4 ^ 2

4: 0100

2: 0010

XOR

   0110 => 6

But 

2: 0010

2: 0010

XOR

   0000 => 0

[Algorithm] 136. Single Number

标签:output   let   ref   tor   bit   app   exce   col   java   

原文地址:https://www.cnblogs.com/Answer1215/p/11984987.html

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