Skip to content

Commit 2db34c8

Browse files
committedFeb 21, 2021
2021-02-21
1 parent e29a907 commit 2db34c8

File tree

3 files changed

+83
-7
lines changed

3 files changed

+83
-7
lines changed
 

‎1539.第k个缺失的正整数/1539-第k个缺失的正整数.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@ def findKthPositive(self, arr, k):
55
:type k: int
66
:rtype: int
77
"""
8-
cnt = 0
9-
s = set(arr)
10-
for i in range(1, max(arr) + k + 1):
11-
if i not in s:
12-
cnt += 1
13-
if cnt == k:
14-
return i
8+
arr = set(arr)
9+
num = 1
10+
while k:
11+
if num not in arr:
12+
k -= 1
13+
14+
num += 1
15+
return num - 1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution(object):
2+
def canConvertString(self, s, t, k):
3+
"""
4+
:type s: str
5+
:type t: str
6+
:type k: int
7+
:rtype: bool
8+
"""
9+
from collections import defaultdict
10+
11+
if not s or not t or len(s) != len(t):
12+
return False
13+
14+
d = list()
15+
16+
for i in range(len(s)):
17+
if s[i] < t[i]:
18+
d.append(ord(t[i]) - ord(s[i]))
19+
elif s[i] > t[i]:
20+
d.append(26 - ord(s[i]) + ord(t[i]))
21+
22+
d.sort()
23+
res = 0
24+
pre = None
25+
for distance in d:
26+
if not pre or pre != distance:
27+
res = max(res, distance)
28+
pre = distance
29+
pre_cnt = 1
30+
else:
31+
res = max(res, 26 * pre_cnt + distance)
32+
pre_cnt += 1
33+
if res > k:
34+
return False
35+
return True
36+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution(object):
2+
def minInsertions(self, s):
3+
"""
4+
:type s: str
5+
:rtype: int
6+
"""
7+
left_cnt, cons_right_cnt = 0, 0
8+
res = 0
9+
for ch in s:
10+
if ch == "(":
11+
if cons_right_cnt:
12+
if cons_right_cnt % 2: # add 1 to make it even
13+
res += 1
14+
cons_right_cnt += 1
15+
pair = min(left_cnt, cons_right_cnt // 2) # build all possible pairs
16+
left_cnt -= pair
17+
cons_right_cnt -= pair * 2
18+
19+
if cons_right_cnt: # if two or more ) left
20+
res += cons_right_cnt // 2 # add "(" every 2 )
21+
cons_right_cnt = 0
22+
left_cnt += 1
23+
else:
24+
cons_right_cnt += 1
25+
26+
if cons_right_cnt:
27+
if cons_right_cnt % 2: # add 1 to make it even
28+
res += 1
29+
cons_right_cnt += 1
30+
pair = min(left_cnt, cons_right_cnt // 2) # build all possible pairs
31+
left_cnt -= pair
32+
cons_right_cnt -= pair * 2
33+
34+
if cons_right_cnt: # if two or more ) left
35+
res += cons_right_cnt // 2 # add "(" every 2 )
36+
cons_right_cnt = 0
37+
38+
res += left_cnt * 2 # add 2 ) every (
39+
return res

0 commit comments

Comments
 (0)
Please sign in to comment.