LeetCode腾讯50题-Day11-136/141/142

这篇博客介绍了两种LeetCode题目解法:利用位运算找到数组中只出现一次的数字,以及通过双指针判断链表是否存在环。位运算解法在不使用额外空间的情况下实现了线性时间复杂度;链表环检测则通过单指针和双指针策略,高效判断环的存在。
摘要由CSDN通过智能技术生成

LeetCode50题(17天)-Day11

136 只出现一次的数字

  • 题号:136
  • 难度:简单
  • https://leetcode-cn.com/problems/single-number/

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

说明

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,1]
输出: 1

示例 2:

输入: [4,1,2,1,2]
输出: 4

实现

第一种:通过集合的方法

C# 语言

  • 状态:通过
  • 16 / 16 个通过测试用例
  • 执行用时: 136 ms, 在所有 C# 提交中击败了 98.86% 的用户
  • 内存消耗: 26.4 MB, 在所有 C# 提交中击败了 5.34% 的用户
public class Solution
{
    public int SingleNumber(int[] nums)
    {
        HashSet<int> h = new HashSet<int>();
        for (int i = 0; i < nums.Length; i++)
        {
            if (h.Contains(nums[i]))
            {
                h.Remove(nums[i]);
            }
            else
            {
                h.Add(nums[i]);
            }
        }
        return h.ElementAt(0);
    }
}

Python 语言

  • 执行结果:通过
  • 执行用时:60 ms, 在所有 Python3 提交中击败了 55.88% 的用户
  • 内存消耗:15.6 MB, 在所有 Python3 提交中击败了 5.26% 的用户
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        h = set()
        for num in nums:
            if num in h:
                h.remove(num)
            else:
                h.add(num)
        return list(h)[0]

第二种:利用位运算的方法。

A: 00 00 11 00
B: 00 00 01 11

A^B: 00 00 10 11
B^A: 00 00 10 11

A^A: 00 00 00 00
A^0: 00 00 11 00

A^B^A: = A^A^B = B = 00 00 01 11

"异或"操作满足交换律和结合律。

C# 实现

  • 状态:通过
  • 16 / 16 个通过测试用例
  • 执行用时: 144 ms, 在所有 C# 提交中击败了 91.76% 的用户
  • 内存消耗: 25.4 MB, 在所有 C# 提交中击败了 11.39% 的用户
public class Solution
{
    public int SingleNumber(int[] nums)
    {
        int result = 0;
            
        for (int i = 0; i < nums.Length; i++)
        {
            result ^= nums[i];
        }
        return result;
    }
}

Python 实现

  • 执行结果:通过
  • 执行用时:44 ms, 在所有 Python3 提交中击败了 84.17% 的用户
  • 内存消耗:15.3 MB, 在所有 Python3 提交中击败了 5.26% 的用户
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        result = 0
        for item in nums:
            result ^= item
        return result

141 环形链表

  • 题号:141
  • 难度:简单
  • https://leetcode-cn.com/problems/linked-list-cycle/

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

为了表示给定链表中的环,我们使用整数pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果pos是 -1,则在该链表中没有环。

示例 1

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2

输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。

示例 3

输入:head = [1], pos = -1
输出:false
解释:链表中没有环。

进阶

你能用 O(1)(即,常量)内存解决此问题吗?


实现

第一种:通过集合的方法

通过检查一个结点此前是否被访问过来判断链表是否为环形链表。

C# 语言

  • 状态:通过
  • 执行用时:112 ms, 在所有 C# 提交中击败了 84.04% 的用户
  • 内存消耗:26.5 MB, 在所有 C# 提交中击败了 100.00% 的用户
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public bool HasCycle(ListNode head) 
    {
        HashSet<ListNode> h = new HashSet<ListNode>();
        ListNode temp = head;
        while (temp != null)
        {            
            if (h.Contains(temp))
                return true;

            h.Add(temp);
            temp = temp.next;
        }
        return false;        
    }
}

Python 语言

  • 执行结果:通过
  • 执行用时:60 ms, 在所有 Python3 提交中击败了 64.49% 的用户
  • 内存消耗:17.3 MB, 在所有 Python3 提交中击败了 9.52% 的用户
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        h = set()
        temp = head
        while temp is not None:
            if temp in h:
                return True

            h.add(temp)
            temp = temp.next
        return False

第二种:利用双指针的方式

通常情况下,判断是否包含了重复的元素,我们使用Hash的方式来做。对于单链表的这种场景,我们也可以使用双指针的方式。

第一个指针 p1 每次移动两个节点,第二个指针 p2 每次移动一个节点,如果该链表存在环的话,第一个指针一定会再次碰到第二个指针,反之,则不存在环。

比如:head = [1,2,3,4,5],奇数

p1:1   3   5   2   4   1
p2:1   2   3   4   5   1

比如:head = [1,2,3,4],偶数

p1:1   3   1   3   1
p2:1   2   3   4   1

C# 语言

  • 状态:通过
  • 执行用时: 112 ms, 在所有 C# 提交中击败了 98.43% 的用户
  • 内存消耗: 24.9 MB, 在所有 C# 提交中击败了 5.13% 的用户
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public bool HasCycle(ListNode head) {
        ListNode p1 = head;
        ListNode p2 = head;

        while (p1 != null && p1.next != null)
        {
            p1 = p1.next.next;
            p2 = p2.next;
            if (p1 == p2)
                return true;
        }
        return false;
    }
}

Python 语言

  • 执行结果:通过
  • 执行用时:56 ms, 在所有 Python3 提交中击败了 60.97% 的用户
  • 内存消耗:16.6 MB, 在所有 Python3 提交中击败了 11.81% 的用户
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        p1 = head
        p2 = head
        while p1 is not None and p1.next is not None:
            p1 = p1.next.next
            p2 = p2.next
            if p1 == p2:
                return True
        return False

142 环形链表2

  • 题号:142
  • 难度:中等
  • https://leetcode-cn.com/problems/linked-list-cycle-ii/

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

说明:不允许修改给定的链表。

示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2

输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。

示例 3

输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。

进阶:

你是否可以不用额外空间解决此题?


实现

第一种:利用暴力匹配的方式

  • 状态:通过
  • 16 / 16 个通过测试用例
  • 执行用时: 412 ms, 在所有 C# 提交中击败了 17.07% 的用户
  • 内存消耗: 24.8 MB, 在所有 C# 提交中击败了 10.00% 的用户
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode DetectCycle(ListNode head)
    {
        if (head == null)
            return null;

        ListNode p1 = head;
        int i = 0;
        while (p1 != null)
        {
            p1 = p1.next;
            i++;

            ListNode p2 = head;
            int j = 0;
            while (j < i)
            {
                if (p2 == p1)
                {
                    return p2;
                }
                p2 = p2.next;
                j++;
            }
        }
        return null;
    }
}

第二种:通过集合的方法

C# 语言

  • 状态:通过
  • 16 / 16 个通过测试用例
  • 执行用时: 140 ms, 在所有 C# 提交中击败了 82.93% 的用户
  • 内存消耗: 26 MB, 在所有 C# 提交中击败了 5.00% 的用户
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution 
{
    public ListNode DetectCycle(ListNode head) 
    {
        HashSet<ListNode> h = new HashSet<ListNode>();
        ListNode temp = head;
        while (temp != null)
        {            
            if (h.Contains(temp))
                return temp;

            h.Add(temp);
            temp = temp.next;
        }
        return null;  
    }
}

Python 语言

  • 执行结果:通过
  • 执行用时:72 ms, 在所有 Python3 提交中击败了 36.52% 的用户
  • 内存消耗:17.2 MB, 在所有 Python3 提交中击败了 7.69% 的用户
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        h = set()
        temp = head
        while temp is not None:
            if temp in h:
                return temp

            h.add(temp)
            temp = temp.next
        return None
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值