首页>itarticle>xor Intersection of Two Arrays [Happy Number] (https://leetcode.com/explore/learn/card/hash-table/183/combination-with-other-algorithms/1131/)
xor Intersection of Two Arrays [Happy Number] (https://leetcode.com/explore/learn/card/hash-table/183/combination-with-other-algorithms/1131/)
admin11月 14, 20200
1 2 3 4 5 6 7 8 9 10
class { public: intsingleNumber(vector<int>& nums){ int result = 0; for (int num : nums) { result ^= num; } return result; } };
A better explanation why this technique works-
Let’s say we have an array - [2,1,4,5,2,4,1]. What we are doing is essentially this-
class { public: unordered_map<int, int> path; boolisHappy(int n){ int value=0; int key=n; while (n) {//calculate the value of the key. int temp = n%10; value+=temp*temp; n/=10; } if (value==1) {//if the value is 1,the key is a happy number. returntrue; } if (path.count(value) > 0) {//if the value is already in the map,there is a cycle,so the key is not a happy number. returnfalse; } path[key]=value;//put the key/value in the map return isHappy(value);//calculate recursively } };
近期评论