Update from work PC

This commit is contained in:
a.shalimov 2026-02-07 09:19:45 +03:00
parent e478221c98
commit a5169c9b85
5 changed files with 231 additions and 0 deletions

View file

@ -0,0 +1,30 @@
from typing import List
from collections import defaultdict
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
res = []
count_elems = defaultdict(int)
count_in = { i: set() for i in range(0, len(nums) + 1) }
for i in range(0, len(nums)):
cur_char = nums[i]
count_elems[cur_char] += 1
tmp_value = count_elems[cur_char]
count_in[tmp_value].add(cur_char)
count_in[tmp_value - 1].discard(cur_char)
# Начинаем обход count_in с самого большого значения вхождений
for i in range(len(nums), 0, -1):
# Если есть элементы - записываем их в массив res
while len(count_in[i]) > 0:
res.append(count_in[i].pop())
# Уменьшаем значение k
k -=1
if k == 0:
return res
return res
cl = Solution()
print(cl.topKFrequent(nums=[1,1,1,2,2,3], k = 2))
print(cl.topKFrequent(nums=[1], k = 1))
print(cl.topKFrequent(nums = [1,2,1,2,1,2,3,1,3,2], k = 2))

View file

@ -0,0 +1,52 @@
from typing import List
from collections import defaultdict
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = defaultdict(set)
cols = defaultdict(set)
sqrs = defaultdict(set)
for row_count in range(0, len(board)):
for col_count in range(0, len(board[row_count])):
elem = board[row_count][col_count]
if elem == ".":
continue
if elem in rows[row_count] or elem in cols[col_count] or elem in sqrs[(row_count//3, col_count//3)]:
return False
rows[row_count].add(elem)
cols[col_count].add(elem)
sqrs[(row_count//3, col_count//3)].add(elem)
col_count += 1
row_count += 1
return True
cl = Solution()
board = [
["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
]
exp = True
print(f"Exp: {exp}\nRes: {cl.isValidSudoku(board)}")
board = [
["8", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
]
exp = False
print(f"Exp: {exp}\nRes: {cl.isValidSudoku(board)}")

View file

@ -0,0 +1,60 @@
"""
Даны два отсортированных по возрастанию массива nums1 и nums2. Необходимо вернуть новый массив nums3, который содержит все общие элементы из nums1 и nums2.
Результат должен быть также отсортирован по возрастанию. Если элементы встречаются в массивах несколько раз, то их нужно продублировать в ответе.
Пример 1:
Ввод: nums1 = [-3,2,2,5,8,19,31], nums2 = [1,2,2,2,6,19,52]
Вывод: [2,2,19]
Пример 2:
Ввод: nums1 = [-5,4], nums2 = [1,2]
Вывод: []
Пример 3:
Ввод: nums1 = [], nums2 = [1,2]
Вывод: []
Ограничения:
len(nums1), len(nums2) >= 0
"""
from typing import List
def solve(nums1, nums2) -> List:
if len(nums1) == 0 or len(nums2) ==0:
return []
res = []
i, j = 0, 0
while i < len(nums1):
if j >= len(nums2):
break
nums1_num = nums1[i]
nums2_num = nums2[j]
if nums1_num > nums2_num:
j +=1
if nums1_num < nums2_num:
i +=1
if nums1_num == nums2_num:
res.append(nums1[i])
i+=1
j+=1
return res
print(solve(nums1 = [-3,2,2,5,8,19,31], nums2 = [1,2,2,2,6,19,52]))
print([2,2,19])
print("\n")
print(solve(nums1 = [-5,4], nums2 = [1,2]))
print([])
print("\n")
print(solve(nums1 = [], nums2 = [1,2]))
print([])
print("\n")

View file

@ -0,0 +1,45 @@
"""
Даны два массива nums1 и nums2, отсортированные по возрастанию и состоящие из уникальных элементов. Нужно найти все элементы, которые встречаются только в одном из массивов и вернуть их в порядке возрастания.
Пример 1:
Ввод: nums1 = [1,5,7,9], nums2 = [2,3,5,6,7,8]
Вывод: [1,2,3,6,8,9]
Пример 2:
Ввод: nums1 = [2,3], nums2 = [1]
Вывод: [1,2,3]
Ограничения:
len(nums1) + len(nums2) >= 1
"""
def solve(nums1, nums2):
res = []
if len(nums1) > len(nums2):
short = nums2
long = nums1
else:
short = nums1
long = nums2
s, l = 0, 0
while s < len(short):
if short[s] == long[l]:
l+=1
s+=1
elif short[s] < long[l]:
res.append(short[s])
s+=1
elif short[s] > long[l]:
return res
s
1,5,7,9
l
2,3,5,6,7,8
[1,2,3,6,8,9]

View file

@ -0,0 +1,44 @@
"""
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward.
Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 105
s consists only of printable ASCII characters.
"""
"""
Инициализируем i - первый элемент (символ строки), j - последний
Далее будем каждый шаг двигать их к друг другу, пока i > j
По ходу будем:
1. Убеждаться что у нас действительная буква (не символы всякие по типу запятых, пробелов и т.д)
1.1 Если попадается что-то не валидное - двигаем указатель дальше
2. Как только убедились что пришел валидный символ - делаем его lowercase
3. Срваниваем
A man, a plan, a canal: Panama
i j
"""
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return