标签:
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?
异或运算应用:
异或运算满足交换律和结合律, 通过交换元素(如插入排序等)可以使得相同元素相邻,
(x, x), (y, y), ..., sigle, ... , (z, z)
所有元素异或后:(x ^ x) ^ ... ^ single ^ (z ^ z) = 0 ^ ... ^ single ^ ... ^ 0 = single
1 int singleNumber(int A[], int n) 2 { 3 int single = 0; 4 5 for (int i = 0; i < n; i++) 6 single ^= A[i]; 7 8 return single; 9 }
leetcode 136. Single Number && 137. Single Number II
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4230658.html