给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
class Solution {
public:
int singleNumber(vector<int>& nums) {
//异或性质
int res=0;
for(auto x:nums)
{
res^=x;
}
return res;
}
};
给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪next指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数pos来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果pos是-1,则在该链表中没有环。注意:pos不作为参数进行传递,仅仅是为了标识链表的实际情况。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==nullptr)return false;
ListNode*low=head,*fast=head->next;
while(fast!=low)
{
if(fast==nullptr)return false;
low=low->next;
if(fast->next!=nullptr)
fast=fast->next->next;
else{
return false;
}
}
return true;
}
};
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回null。
为了表示给定链表中的环,我们使用整数pos来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果pos是-1,则在该链表中没有环。注意,pos仅仅是用于标识环的情况,并不会作为参数传递到函数中。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==nullptr||head->next==nullptr)return nullptr;
ListNode*fast=head,*slow=head;
fast=fast->next->next;
slow=slow->next;
while(slow!=fast)
{
if(fast==nullptr||fast->next==nullptr) return nullptr;
slow=slow->next;
fast=fast->next->next;
}
ListNode*p=head;
while(p!=slow)
{
p=p->next;
slow=slow->next;
}
return p;
}
};
};