目前我所做的蓄水池问题一共有三题,后续会慢慢更新
题目一、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