题解 | #数组中只出现一次的两个数字#
数组中只出现一次的两个数字
http://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param array int整型vector * @return int整型vector */ vector<int> FindNumsAppearOnce(vector<int>& array) { int tmp = 0; for(int i=0; i<array.size(); i++){ tmp ^= array[i]; } int mask = 1; while((mask&tmp) == 0) mask <<= 1; int a = 0; int b = 0; for(int i=0; i<array.size(); i++){ if((mask&array[i]) == 0){ a ^= array[i]; } else{ b ^= array[i]; } } if(a > b){ swap(a, b); } return {a, b}; // write code here } };
public int[] FindNumsAppearOnce (int[] array) { // 先将全部数进行异或运算,得出最终结果 int tmp = 0; for(int num: array){ tmp ^= num; } // 找到那个可以充当分组去进行与运算的数 // 从最低位开始找起 int mask = 1; while((tmp&mask) == 0){ mask <<= 1; } // 进行分组,分成两组,转换为两组 求出现一次的数字 去求 int a = 0; int b = 0; for(int num:array){ if((num&mask) == 0){ a ^= num; }else{ b ^= num; } } // 因为题目要求小的数放前面,所以这一做个判断 if(a > b){ int c = a; a = b; b = c; } return new int[]{a,b}; }
https://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8?tpId=295&tqId=1375231&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj%3Ftab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D295