leetcode 136. Single Number | XOR的巧妙运用

来源:互联网 发布:智能时代之数据化企业 编辑:程序博客网 时间:2024/05/17 23:16

Description

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?

My solution:None

题目要求O(n),以及不开辟更多内存.
- 关于时间复杂度
1. 对于A[i],同其余进行比较,遍历一次即O(n);
2. 对于A[j],也要像上述步骤一样进行,即使不再同A[i]进行比较,综合起来也是O(n2)的复杂度;
3. 考虑归并等适用于排序的算法思路,未果;
4. 但由3注意到可以先对A进行排序,快速排序在nlog(n)级别,排序之后相邻两两比较,复杂度在O(n),综合为nlog(n)
5. 通过Discuss才意识到通过位运算将神速! 这也是题目中给定的是twice,而不是3/4/5… 等,要从两两相消,单个的消不掉这个角度思考!!!

Discuss

int singleNumber(int A[], int n) {    int result = 0;    for (int i = 0; i<n; i++)    {        result ^=A[i];    }    return result;}

known that A XOR A = 0
Exclusive disjunction is often used for bitwise operations.
Examples:
1 XOR 1 = 0
1 XOR 0 = 1
0 XOR 1 = 1
0 XOR 0 = 0

小结:
1. 1110 XOR 1001 = 0111 (this is equivalent to addition without carry).(注意到0+0=0,1+1=0的二进制法则刚好和xor一致)
2. 注意到 0 ^ N = N (N=0,1),不仅对于一个bit成立,故有0^A=A
3. A^B^A=B

参考

  • XOR

  • leetcode 136

原创粉丝点击