只出现一次的数字
class Solution {
public:
int singleNumber(vector& nums) {
int ret=0;
for(auto e:nums) ret^=e;
return ret;
}
};
异或运算三个性质
1 任何数和0做异或结果还是原来的数
2 任何数和自身做异或结果为0
3 异或运算满足交换律和结合律
环形链表
class Solution {
public:
bool hasCycle(ListNode head) {
if(headnullptr||head->nextnullptr){
return false;
}
ListNode fast=head;
ListNode* slow=head;
while((fast!=nullptr)&&(fast->next!=nullptr)){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
return true;
}
}
return false;
}
};//龟兔赛跑
环形链表2
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast=head;
ListNode *slow=head;
while(fast!=nullptr&&fast->next!=nullptr){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
ListNode *index1=fast;
ListNode *index2=head;
while(index1!=index2){
index2=index2->next;
index1=index1->next;
}
return index2;
}
}
return nullptr;
}
};
判断有环操作与第一个环形链表类似,但是在fast与slow相遇那个点上并不一定是入口。根据计算得出从头结点出发和从fast和slow相遇那个节点同时出发那么他们两个相遇的节点就是入口。