Skip to content

Commit 5650e7d

Browse files
committed
add three algo in the array section
1 parent fb195d2 commit 5650e7d

3 files changed

Lines changed: 100 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
Find the majority element in an array.
3+
"""
4+
5+
def majority_element(nums: list[int]) -> int:
6+
"""
7+
Find the element that appears more than n/2 times using
8+
Boyer-Moore Voting Algorithm.
9+
10+
Args:
11+
nums: List of integers.
12+
13+
Returns:
14+
The majority element.
15+
16+
Examples:
17+
>>> majority_element([3, 2, 3])
18+
3
19+
>>> majority_element([2, 2, 1, 1, 1, 2, 2])
20+
2
21+
"""
22+
count = 0
23+
candidate = None
24+
25+
for num in nums:
26+
if count == 0:
27+
candidate = num
28+
count += (1 if num == candidate else -1)
29+
30+
return candidate
31+
32+
33+
if __name__ == "__main__":
34+
import doctest
35+
doctest.testmod()
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
Find the maximum subarray sum (Kadane's Algorithm).
3+
"""
4+
5+
def max_subarray(nums: list[int]) -> int:
6+
"""
7+
Find the contiguous subarray with the largest sum.
8+
9+
Args:
10+
nums: List of integers.
11+
12+
Returns:
13+
Maximum sum of subarray.
14+
15+
Examples:
16+
>>> max_subarray([-2,1,-3,4,-1,2,1,-5,4])
17+
6
18+
>>> max_subarray([1])
19+
1
20+
>>> max_subarray([5,4,-1,7,8])
21+
23
22+
"""
23+
max_sum = current_sum = nums[0]
24+
25+
for num in nums[1:]:
26+
current_sum = max(num, current_sum + num)
27+
max_sum = max(max_sum, current_sum)
28+
29+
return max_sum
30+
31+
32+
if __name__ == "__main__":
33+
import doctest
34+
doctest.testmod()
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
Rotate an array to the right by k steps.
3+
"""
4+
5+
def rotate(nums: list[int], k: int) -> list[int]:
6+
"""
7+
Rotate the array to the right by k steps.
8+
9+
Args:
10+
nums: List of integers.
11+
k: Number of steps to rotate.
12+
13+
Returns:
14+
The rotated list.
15+
16+
Examples:
17+
>>> rotate([1,2,3,4,5,6,7], 3)
18+
[5, 6, 7, 1, 2, 3, 4]
19+
20+
>>> rotate([-1,-100,3,99], 2)
21+
[3, 99, -1, -100]
22+
"""
23+
n = len(nums)
24+
k = k % n # In case k > n
25+
nums[:] = nums[-k:] + nums[:-k]
26+
return nums
27+
28+
29+
if __name__ == "__main__":
30+
import doctest
31+
doctest.testmod()

0 commit comments

Comments
 (0)