leetcode#136 Single Number

来源:互联网 发布:加入域找不到网络路径 编辑:程序博客网 时间:2024/05/14 06:58

github链接

本题leetcode链接

题目描述

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?
Tag: hashTable Bit manipulation

题目分析

有一个数组,里面除以一个只出现一次的元素外,其他所有元素都出现了两次。要求找出这个元素。要求时间复杂度为O(n)。最好不要使用额外的空间。
题目提示了使用位操作。
异或操作满足下面的性质:

  1. 交换律
  2. 结合律
  3. 0和任何数异或等于任何数本身
  4. 两个相等的数异或等于0

举个例子模拟一下

  • 假设数组为 2 6 8 9 4 3 4 2 6 8 9,我们要找的元素是3
  • 把所有元素异或得到2^6^8^9^4^3^4^2^6^8^9
  • 应用交换律和结合律,得到(2^2)^(6^6)^(8^8)^(9^9)^(4^4)^3
  • 应用性质3,得到0^0^0^0^0^3
  • 应用性质4,得到3

把所有元素异或起来,因为相同的数异或结果为0,最后的结果肯定就是没有相同元素和它异或的那个元素,也就是我们要找的只出现一次的元素。

代码实现(JAVA)

int singleNumber(int A[], int n) {    int i = 0;    int result = 0;    for(i=0;i<n;i++)        result = result^A[i];    return result;}
0 0
原创粉丝点击