LeetCode 367. Valid Perfect Square

Post by ailswan Dec. 13, 2023

367. Valid Perfect Square

Problem Statement

link: LeetCode.cn LeetCode

Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.

Implement the Solution class:

Solution(ListNode head) Initializes the object with the head of the singly-linked list head. int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.

Example:

Input: ["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"][[[1, 2, 3]], [], [], [], [], []] Output: [null, 1, 3, 2, 2, 3]

Solution Approach

Algorithm

Implement

    class Solution:
  def isPerfectSquare(self, num: int) -> bool:
    l, r = 0, num
    while l <= r:
      m = (l + r) // 2
      t = m * m
      if t == nums:
        return True
      if t < num:
        l = m + 1
      else: 
        r = m - 1
    return False