Skip to content

Commit 5369939

Browse files
committedNov 1, 2024
[Feat] Add more implementation
1 parent 291b613 commit 5369939

4 files changed

+63
-0
lines changed
 

Diff for: ‎191-NumberOf1Bits.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Solution:
2+
def hammingWeight(self, n: int) -> int:
3+
result = 0
4+
binString = bin(n)
5+
for char in binString:
6+
if char == "1":
7+
result += 1
8+
9+
return result

Diff for: ‎347-TopKFrequentElements.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution:
2+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3+
hashMap = {}
4+
for num in nums:
5+
if num not in hashMap:
6+
hashMap[num] = 1
7+
else:
8+
hashMap[num] += 1
9+
10+
freq = [[] for i in range(len(nums) + 1)]
11+
for n, val in hashMap.items():
12+
freq[val].append(n)
13+
14+
res = []
15+
for i in range(len(freq) - 1, 0, -1):
16+
for n in freq[i]:
17+
res.append(n)
18+
if len(res) == k:
19+
return res

Diff for: ‎53-MaximumSubarray.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def maxSubArray(self, nums: List[int]) -> int:
3+
maxSum = nums[0]
4+
tempSum = 0
5+
6+
for num in nums:
7+
if tempSum < 0:
8+
tempSum = 0
9+
tempSum += num
10+
maxSum = max(maxSum, tempSum)
11+
return maxSum

Diff for: ‎543-DiameterOfBinaryTree.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def __init__(self):
9+
self.max_diameter = 0
10+
11+
def dfs(self, root: Optional[TreeNode]) -> int:
12+
if root == None:
13+
return 0
14+
15+
leftDiameter = self.dfs(root.left)
16+
rightDiameter = self.dfs(root.right)
17+
18+
self.max_diameter = max(self.max_diameter, leftDiameter + rightDiameter)
19+
20+
return 1 + max(leftDiameter, rightDiameter)
21+
22+
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
23+
self.dfs(root)
24+
return self.max_diameter

0 commit comments

Comments
 (0)
Please sign in to comment.