Skip to content

Commit 45fa85d

Browse files
committed
Upload on 3/10
1 parent 3af3a5a commit 45fa85d

File tree

4 files changed

+93
-0
lines changed

4 files changed

+93
-0
lines changed

13. Roman to Integer.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
3+
def romanToInt(self, s):
4+
"""
5+
:type s: str
6+
:rtype: int
7+
"""
8+
s = str(s)
9+
lst1 = {'CM': 900, 'CD': 400, 'XL': 40, 'XC': 90, 'IV': 4, 'IX': 9}
10+
lst2 = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
11+
12+
if not s:
13+
return 0
14+
if len(s) == 1:
15+
return lst2[s]
16+
i = 0
17+
sum = 0
18+
while i <= len(s) - 1:
19+
if len(s[i:]) >= 2 and s[i:i + 2] in lst1:
20+
sum += lst1[s[i:i + 2]]
21+
i += 2
22+
else:
23+
sum += lst2[s[i]]
24+
i += 1
25+
return sum

14. Longest Common Prefix.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
3+
def longestCommonPrefix(self, strs: List[str]) -> str:
4+
if not strs:
5+
return ""
6+
steps = len(strs[0])
7+
t_flag = False
8+
prefix = ""
9+
for i in range(steps):
10+
for j in range(1, len(strs)):
11+
if len(strs[j]) > i:
12+
if strs[j][i] != strs[0][i]:
13+
t_flag = True
14+
break
15+
else:
16+
t_flag = True
17+
break
18+
if t_flag:
19+
break
20+
else:
21+
prefix = prefix + strs[0][i]
22+
23+
return prefix

15. 3Sum.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
3+
def threeSum(self, nums: List[int]) -> List[List[int]]:
4+
res = []
5+
nums.sort()
6+
N = len(nums)
7+
for i in range(N):
8+
if i > 0 and nums[i] == nums[i - 1]:
9+
continue
10+
target = -nums[i]
11+
s = i + 1
12+
e = N - 1
13+
while s < e:
14+
if nums[s] + nums[e] == target:
15+
res.append([nums[i], nums[s], nums[e]])
16+
s += 1
17+
while s < e and nums[s] == nums[s - 1]:
18+
s += 1
19+
elif nums[s] + nums[e] < target:
20+
s += 1
21+
else:
22+
e -= 1
23+
return res

16. 3Sum Closest.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
3+
def threeSumClosest(self, nums: List[int], target: int) -> int:
4+
nums.sort()
5+
N = len(nums)
6+
closest = (float("inf"), 0)
7+
for i in range(N):
8+
new_target = target - nums[i]
9+
s = i + 1
10+
e = N - 1
11+
while s < e:
12+
diff = new_target - nums[s] - nums[e]
13+
if diff == 0:
14+
return target
15+
abs_diff = abs(diff)
16+
if abs_diff < closest[0]:
17+
closest = (abs_diff, nums[i] + nums[s] + nums[e])
18+
if diff > 0:
19+
s += 1
20+
else:
21+
e -= 1
22+
return closest[1]

0 commit comments

Comments
 (0)