LeetCode|Python|400题分类刷题记录——并查集

 并查集

不断更新中...

323. 无向图中连通分量的数目

给定编号从 0 到 n-1 的 n 个节点和一个无向边列表(每条边都是一对节点),请编写一个函数来计算无向图中连通分量的数目。

示例 1:

输入: n = 5 和 edges = [[0, 1], [1, 2], [3, 4]]

     0          3
     |          |
     1 --- 2    4 

输出: 2
示例 2:

输入: n = 5 和 edges = [[0, 1], [1, 2], [2, 3], [3, 4]]

     0           4
     |           |
     1 --- 2 --- 3

输出:  1
注意:
你可以假设在 edges 中不会出现重复的边。而且由于所以的边都是无向边,[0, 1] 与 [1, 0]  相同,所以它们不会同时在 edges 中出现。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-connected-components-in-an-undirected-graph
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:经典的并查集问题 

class Solution:
    def initFather(self, n):
        self.father = [0] * n
        for i in range(n):
            self.father[i] = i 

    def findFather(self, x):
        temp = x
        while x != self.father[x]:  # 找到x的根节点
            x = self.father[x]
        while temp != self.father[temp]:  # 路径压缩
            z = temp
            temp = self.father[temp]
            self.father[z] = x
        return x
    
    def unionSet(self, a, b):  # 合并集合
        a_father = self.findFather(a)
        b_father = self.findFather(b)
        if a_father != b_father:
            self.father[a_father] = b_father

    def countComponents(self, n: int, edges: List[List[int]]) -> int:
        self.initFather(n)
        is_root = [0] * n

        for edge in edges:
            self.unionSet(edge[0], edge[1])
        for i in range(n):
            r = self.findFather(i)
            is_root[r] = 1  # 如果要得到每个集合包含的元素个数,则改为is_root[r] += 1,然后输出
        print(is_root)
        count = sum(is_root)
        return count

 六、贪心

55. 跳跃游戏

给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标。

示例 1:

输入:nums = [2,3,1,1,4]
输出:true
解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
示例 2:

输入:nums = [3,2,1,0,4]
输出:false
解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
 

提示:

1 <= nums.length <= 3 * 104
0 <= nums[i] <= 105

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路: 这道题只用考虑每一个下标对应的范围是否能到达终点,只要存在其中一个下标的最大范围能够到达终点则意味着我从起始点是可以到终点的,而不用管具体每一步怎么走。

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        if len(nums) == 1:
            return True
        max_range = 0
        i = 0
        while i <= max_range:
            max_range = max(max_range, i + nums[i])  # 更新当前可以走的最大范围的右边界
            if max_range >= len(nums) - 1:  # 如果最大范围可以让我直接到达终点,则直接返回true
                return True
            i += 1
        return False  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值