leetcode腾讯50题-136-141-142

136. 只出现一次的数字

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

class Solution {

public:

    int singleNumber(vector<int>& nums) {

        //异或性质

        int res=0;

        for(auto x:nums)

        {

            res^=x;

        }

        return res;

    }

};

141. 环形链表

给定一个链表,判断链表中是否有环。

如果链表中有某个节点,可以通过连续跟踪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;

    }

};

142. 环形链表 II

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回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;

    }

};

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容