Skip to content

Commit e27e30e

Browse files
committed
add linked list and simple summaryranges
1 parent 209bf82 commit e27e30e

3 files changed

Lines changed: 161 additions & 0 deletions

File tree

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# You are given a sorted unique integer array nums.
2+
#
3+
# A range [a,b] is the set of all integers from a to b (inclusive).
4+
#
5+
# Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.
6+
#
7+
# Each range [a,b] in the list should be output as:
8+
# "a->b" if a != b
9+
# "a" if a == b
10+
11+
# Example 1:
12+
#
13+
# Input: nums = [0,1,2,4,5,7]
14+
# Output: ["0->2","4->5","7"]
15+
# Explanation: The ranges are:
16+
# [0,2] --> "0->2"
17+
# [4,5] --> "4->5"
18+
# [7,7] --> "7"
19+
#
20+
# Example 2:
21+
#
22+
# Input: nums = [0,2,3,4,6,8,9]
23+
# Output: ["0","2->4","6","8->9"]
24+
# Explanation: The ranges are:
25+
# [0,0] --> "0"
26+
# [2,4] --> "2->4"
27+
# [6,6] --> "6"
28+
# [8,9] --> "8->9"
29+
#
30+
31+
from typing import List
32+
33+
def summaryRanges(nums: List[int]) -> List[str]:
34+
if nums:
35+
dp = []
36+
length_num = len(nums)
37+
a_val = nums[0]
38+
for index, current_val in enumerate(nums):
39+
if index > length_num - 1:
40+
break
41+
else:
42+
next_val = nums[index+1] if index != length_num -1 else nums[index]
43+
b_val = current_val
44+
if current_val + 1 != next_val:
45+
if a_val != b_val:
46+
dp.append(f"{a_val}->{b_val}")
47+
else:
48+
dp.append(f"{a_val}")
49+
a_val = next_val
50+
return dp
51+
else:
52+
return nums
53+
54+
if __name__ == "__main__":
55+
print(summaryRanges(nums=[1,2,3,5,6,9]))
56+
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
2+
# Задача: K-ый наименьший элемент
3+
4+
# Описание:
5+
# Вам дан корень head бинарного дерева поиска (BST) и число k.
6+
# Необходимо найти k-ый (нумерация с единицы) наименьший элемент в этом дереве поиска.
7+
8+
# Каждый узел дерева задается экземпляром класса Node, определенным ниже:
9+
10+
# Example №1: head = [3,1,4,null,2], k = 1. Ответ: 1
11+
# Example №2: head = [5,3,6,2,4,null,null,1], k = 3. Ответ: 3
12+
13+
from typing import List, Optional
14+
15+
class Node:
16+
def __init__(self, val=0, left=None, right=None):
17+
self.val = val
18+
self.left = left
19+
self.right = right
20+
21+
def inorder(head: Node) -> List[int]:
22+
stack = []
23+
ans = []
24+
curr = head
25+
while curr is not None or len(stack) > 0:
26+
while curr is not None:
27+
stack.append(curr)
28+
curr = curr.left
29+
30+
curr = stack.pop()
31+
ans.append(curr.val)
32+
33+
curr = curr.right
34+
return ans
35+
36+
37+
38+
def kth_smallest(head: Optional[Node], k: int) -> Optional[int]:
39+
if head is not None:
40+
return inorder(head=head)[k-1]
41+
else:
42+
return head
43+
44+
45+
# if __name__ == "__main__":
46+
# example = Node(val= 5,
47+
# left=Node(val=3, right=Node(val=4),
48+
# left=Node(val=2,
49+
# left=Node(val=1))),
50+
# right=Node(val=6))
51+
# print(kth_smallest(head=example, k=1))
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Task name: Поворот односвязного списка
2+
# Desc general: Вам дана голова односвязного списка head.
3+
# Вам необходимо «повернуть» его направо на k позиций.
4+
5+
6+
# Example: 1 - 2 - 3 - 4 - 5
7+
# Example solution: 4 - 5 - 1 - 2 - 3
8+
9+
# Task description:
10+
# Напишите функцию rotate_right(head, k),
11+
# которая будет возвращать голову повернутого листа.
12+
# Вам нельзя создавать новый односвязный список — нужно все изменения делать с существующим
13+
# (т.е. переставлять связи внутри него).
14+
15+
# Считайте, что односвязный список задан классом Node
16+
# (при этом head есть экземпляр данного класса), код которого дан ниже.
17+
18+
from typing import Optional, Tuple
19+
20+
21+
# class Node:
22+
# def __init__(self, value, next=None):
23+
# self.value = value
24+
# self.next = next
25+
26+
def rotate_right(head, k):
27+
if not head or k <= 0:
28+
return head
29+
30+
# Step 1: Find the length of the linked list
31+
length = 1
32+
tail = head
33+
while tail.next:
34+
length += 1
35+
tail = tail.next
36+
37+
# Step 2: Find the new tail (node before the new head)
38+
new_tail = head
39+
for _ in range(length - k - 1):
40+
new_tail = new_tail.next
41+
42+
# Step 3: Detach and move the last k nodes to front
43+
new_head = new_tail.next
44+
new_tail.next = None
45+
tail.next = head
46+
47+
return new_head
48+
49+
50+
# if __name__ == "__main__":
51+
# example = Node(1, Node(2, Node(3, Node(4, Node(5)))))
52+
# solution = Node(5, Node(4, Node(1, Node(2, Node(3)))))
53+
# tmp = rotate_right(example, 1)
54+
# print("stop")

0 commit comments

Comments
 (0)