23.05.10 Today’s Leetcode
59. Spiral Matrix II (medium)
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
arr = [[0 for x in range(n)] for y in range(n)]
# dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]
dirs = [0, 1, 0, -1, 0]
p = 0
cur = [0, 0]
for i in range(n ** 2):
next_ = [cur[0] + dirs[p], cur[1] + dirs[p + 1]]
if next_[0] < 0 or next_[0] >= n or next_[1] < 0 or next_[1] >= n:
p = (p + 1) % 4
next_ = [cur[0] + dirs[p], cur[1] + dirs[p + 1]]
elif arr[next_[0]][next_[1]] != 0:
p = (p + 1) % 4
next_ = [cur[0] + dirs[p], cur[1] + dirs[p + 1]]
arr[cur[0]][cur[1]] = i + 1
cur = next_
return arr
393. UTF-8 Validation (medium)
class Solution:
def validUtf8(self, data: List[int]) -> bool:
# Initialize a counter variable
count = 0
# Iterate through each integer in the input data list
for num in data:
# If the count is 0, check how many leading 1's there are in the current integer
if count == 0:
if (num >> 5) == 0b110:
count = 1
elif (num >> 4) == 0b1110:
count = 2
elif (num >> 3) == 0b11110:
count = 3
elif (num >> 7) != 0:
return False
# If the count is not 0, check if the current integer is a continuation byte
else:
if (num >> 6) != 0b10:
return False
count -= 1
# If the count is still not 0 after iterating through all the integers, it is invalid
return count == 0
384. Shuffle an Array (medium)
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
self.original = list(nums)
def reset(self) -> List[int]:
self.nums = list(self.original)
return self.nums
def shuffle(self) -> List[int]:
n = len(self.nums)
for i in range(n):
# Choose a random index j from i to n-1
j = random.randrange(i, n)
# Swap nums[i] and nums[j]
self.nums[i], self.nums[j] = self.nums[j], self.nums[i]
return self.nums