1、用昨天学到的unordered_set来做!成功!
把A表装到set中,再遍历B表去set里找有没有重复的。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
unordered_set<ListNode*> hashtable;
for(;headA!=NULL; headA=headA->next){
hashtable.insert(headA);
}
for(;headB!=NULL; headB=headB->next){
if(hashtable.count(headB)>0){
cout << "Intersected at '" << headB->val << "'" << endl;
return headB;
}
}
return NULL;
}
};
2、果然我还是弟弟,精选用了快慢针来做。慢针、快针进行比较,判断陷入循环是由1引起的还是别的数引起的。
class Solution {
public:
int bitSquareSum(int n) {
int sum = 0;
while(n > 0)
{
int bit = n % 10;
sum += bit * bit;
n = n / 10;
}
return sum;
}
bool isHappy(int n) {
int slow = n, fast = n;
do{
slow = bitSquareSum(slow);
fast = bitSquareSum(fast);
fast = bitSquareSum(fast);
}while(slow != fast);
return slow == 1;
}
};