LeetCode专题--蓄水池问题

目前我所做的蓄水池问题一共有三题,后续会慢慢更新

题目一、398随机数索引

                                       

思路

解法1

遍历nums,记录所有的索引位置,然后通过random.sample() 返回一个结果。通过candid这个数组保存所有相对应的索引值,

这些索引值作为 random.sample 采样的标准。

在解题的过程,还是选择使用直接方法会来得轻松+愉快

import random

class Solution:

    def __init__(self, nums: List[int]):
        self.nums = nums

    def pick(self, target: int) -> int:
        candid =[]
        for i in range(len(self.nums)):
            if self.nums[i] == target:
                candid.append(i)
        return random.sample(candid, 1)[0]

题目二、382 链表的随机节点

                                                  

思路

解法1

遍历所有链表的节点,将所有的链表节点放入到一个list中,后使用相同的 random.sample() 的方法返回相应的结果

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
import random

class Solution:

    def __init__(self, head: ListNode):
        """
        @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node.
        """
        self.head = head
        self.candid = []
        while self.head:
            self.candid.append(self.head.val)
            self.head = self.head.next
        

    def getRandom(self) -> int:
        """
        Returns a random node's value.
        """        
        return random.choice(self.candid)
        


# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()

题目三、42 接雨水问题

                                                   

思路

解法1

看了大神的解法,将两次遍历解决至此,实在是佩服,ans是存储的雨水,h1相当于左指针,h2相当于右指针,左右指针与下面所走的步伐所围起来就是1,所以,左边+右边减去中间的一个高度,加上之前存储的雨水

class Solution:
    def trap(self, height: List[int]) -> int:
        ans = 0
        h1 = 0
        h2 = 0
        for i in range(len(height)):
            h1 = max(h1, height[i])    # 左边一直往右走
            h2 = max(h2, height[-i-1])   # 右边一直往左走
            ans = ans + h1 + h2 - height[i]
        return ans - len(height) * h1

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值