剑指offer:数组中只出现一次的数字

阳光穿透心脏的1/2处 2022-04-10 09:17 259阅读 0赞

题目描述

一个整型数组里除了两个数字之外,其他的数字都出现了偶数次。请写程序找出这两个只出现一次的数字。

解题思路:

先将所有数字进行异或, 异或结果=两个只出现一次的数字异或的结果,找到异或结果中1出现的第一个位置,根据此位是否为1将数组分为两个组分别进行异或,得到两个数字即为两个单独的数字!

AC C++ Solution:

  1. class Solution {
  2. public:
  3. void FindNumsAppearOnce(vector<int> data,int* num1,int* num2) {
  4. if(data.size() < 2)
  5. return;
  6. int resultExclusiveOR = 0;
  7. for(int i = 0; i < data.size(); i++){
  8. resultExclusiveOR ^= data[i]; //全部异或的结果=两个单独数异或的结果
  9. }
  10. unsigned int index = FindFirstBitIs1(resultExclusiveOR);//找到异或数中第一位为1的位置
  11. *num1 = *num2 = 0;
  12. for(int j = 0; j < data.size(); j++){
  13. if(IsBit1(data[j], index)) //index把数组分为两组,一组的index位为1
  14. *num1 ^= data[j];
  15. else //一组的index位为0
  16. *num2 ^= data[j];
  17. }
  18. }
  19. unsigned int FindFirstBitIs1(int num){
  20. int indexBit = 0;
  21. while(((num & 1) == 0) && (indexBit < 8*sizeof(int))){
  22. num = num >> 1;
  23. indexBit++;
  24. }
  25. return indexBit;
  26. }
  27. bool IsBit1(int num, unsigned int indexBit){
  28. num = num >> indexBit;
  29. return (num&1);
  30. }
  31. };

发表评论

表情:
评论列表 (有 0 条评论,259人围观)

还没有评论,来说两句吧...

相关阅读