题目:
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
解题思路:
这题比Single Number稍难些,不能用异或解决,但排序和bitmap还是可以的,只是时间复杂度和空间复杂度要多些
这里我用另一种方式实现,根据所给数组中元素的规律,可利用每一bit位上1的个数进行解决,直接看代码吧
实现代码:
#include <iostream> using namespace std; /* Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? */ class Solution { public: int singleNumber(int A[], int n) { int once = 0; for(int i = 0; i < 32; i++) { int one_num = 0;//bit为第i位1的个数 for(int j = 0; j < n; j++) if((A[j] >> i) & 1 == 1) one_num++; //因为数组中只有一个数出现一次,其他数都出现三次, //所以除非要找数的当前bit位为1,否则one_num为3的倍数 if(one_num % 3) once += (1 << i); } return once; } }; int main(void) { int arr[] = {2,4,5,5,4,1,2,4,2,5}; int len = sizeof(arr) / sizeof(arr[0]); Solution solution; int once = solution.singleNumber(arr, len); cout<<once<<endl; return 0; }