136. Single Number

来源:互联网 发布:python 实现http接口 编辑:程序博客网 时间:2024/06/07 01:42

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?
算法时间复杂度O(N),不引入额外的存储空间

解决思路:两个相同的值异或为0,4^4 = 4,对数组内所有值异或求值,结果为出现一次的值

/** * @param {number[]} nums * @return {number} */var singleNumber = function(nums) {  return nums.reduce((cal, cur) => {      return cal ^ cur  })};
0 0
原创粉丝点击