Single Number I
问题描述:
Given an array of integers, every element appears twice except for one. Find that single one.
解题思路:
既然除了某个元素出现一次外,其他所有元素都出现两次,那么可以异或数组的所有元素,得到的结果就是我们所要找的那个元素的值。
class Solution { public: int singleNumber(int A[], int n) { if (0 == n) return 0; int result = A[0], i; for (i = 1; i < n; i++) result ^= A[i]; return result; } };
问题描述:
Given an array of integers, every element appears three times except for one. Find that single one.
解题思路:
如果某个元素出现1次,而其他元素都出现3次,那么对所有元素的每个位进行求和,然后对3取余,得到的就是我们要找的元素相应位的值。
class Solution { public: int singleNumber(int A[], int n) { int count[32] = {0}; int result = 0; for (int i = 0; i < 32; i++) { for (int j = 0; j < n; j++) { if ((A[j] >> i) & 1) { count[i]++; } } result |= ((count[i] % 3) << i); } return result; } };
Single Number I & II,布布扣,bubuko.com
原文:http://blog.csdn.net/wan_hust/article/details/38295121