[leetcode] 136 single number
2017-07-20 15:38
423 查看
题目:
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),并且空间复杂度为O(1),使得不能用排序方法,也不能使用map数据结构。那么只能另辟蹊径,需要用位操作Bit Operation来解此题,由于数字在计算机是以二进制存储的,每位上都是0或1,如果我们把两个相同的数字异或,0与0异或是0,1与1异或也是0,那么我们会得到0。根据这个特点,我们把数组中所有的数字都异或起来,则每对相同的数字都会得0,然后最后剩下来的数字就是那个只有1次的数字。异或的性质1:交换律a
^ b = b ^ a,性质2:0 ^ a = a。于是利用交换律可以将数组假想成相同元素全部相邻,于是将所有元素依次做异或操作,相同元素异或为0,最终剩下的元素就为Single Number。
对于实例{2,1,4,5,2,4,1}就会有这样的结果:
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),并且空间复杂度为O(1),使得不能用排序方法,也不能使用map数据结构。那么只能另辟蹊径,需要用位操作Bit Operation来解此题,由于数字在计算机是以二进制存储的,每位上都是0或1,如果我们把两个相同的数字异或,0与0异或是0,1与1异或也是0,那么我们会得到0。根据这个特点,我们把数组中所有的数字都异或起来,则每对相同的数字都会得0,然后最后剩下来的数字就是那个只有1次的数字。异或的性质1:交换律a
^ b = b ^ a,性质2:0 ^ a = a。于是利用交换律可以将数组假想成相同元素全部相邻,于是将所有元素依次做异或操作,相同元素异或为0,最终剩下的元素就为Single Number。
对于实例{2,1,4,5,2,4,1}就会有这样的结果:
(2^1^4^5^2^4^1) => ((2^2)^(1^1)^(4^4)^(5)) => (0^0^0^5) => 5
public int singleNumber(int[] nums){ int res=0; for(int num:nums) res^=num; return res; }
相关文章推荐
- [LeetCode]题解(python):136-Single Number
- 【LeetCode-面试算法经典-Java实现】【136-Single Number(仅仅出现一次的数字)】
- [leetcode]: 136. Single Number
- leetcode 136-Single Number
- 【leetcode】136. Single Number
- Leetcode——136. Single Number
- 【LeetCode】136. Single Number
- [ LeetCode ] - 136. Single Number 解答
- 【leetcode】136. Single Number
- LeetCode 136 Single Number 出现一次的数字
- Leetcode刷题记——136. Single Number(单独的数字)
- LeetCode - 136. Single Number
- leetcode 136 Single Number, 260 Single Number III
- LeetCode_136-Single Number
- [leetcode] 【数组】 136. Single Number
- LeetCode 136. Single Number
- LeetCode 136:Single Number
- [leetcode]--136. Single Number
- LeetCode 136. Single Number
- LeetCode——136. Single Number