Skip to content

Commit 6058fc6

Browse files
committed
l33t
1 parent e4e215a commit 6058fc6

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

1512-num_of_good_pairs.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
https://leetcode.com/problems/number-of-good-pairs/submissions/
3+
4+
Strat:
5+
Since we only have to calculate the # of good pairs (instead of find all
6+
the good pairs themselves), we can employ a trick: given [1, 1, 1, 1], the
7+
number of good pairs for the first 1 is 3 (all the 1s preceding it). The
8+
number of good pairs for the second 1 is 2 (all the 1s preceding it).
9+
Apply this trick for the rest of the 1s, and the pattern of
10+
1 + 2 + 3 + ... + n = (n)(n-1)/2 emerges.
11+
12+
So use a dictionary to count the number of occurances for each #. Iterate through
13+
all the counts, and apply the above series.
14+
15+
Stats:
16+
Runtime: 16 ms, faster than 98.00% of Python online submissions for Number of Good Pairs.
17+
Memory Usage: 12.7 MB, less than 100.00% of Python online submissions for Number of Good Pairs.
18+
"""
19+
class Solution(object):
20+
def numIdenticalPairs(self, nums):
21+
"""
22+
:type nums: List[int]
23+
:rtype: int
24+
"""
25+
nums_counts = {}
26+
27+
for num in nums:
28+
nums_counts[num] = nums_counts.get(num, 0) + 1
29+
30+
result = 0
31+
for count in nums_counts.values():
32+
result += self.count_good_pairs(count)
33+
34+
return result
35+
36+
37+
def count_good_pairs(self, count):
38+
return count * (count - 1) / 2
39+

344-reverse_string.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
https://leetcode.com/problems/reverse-string/submissions/
3+
4+
Strat:
5+
Use two pointers, and narrow in on results.
6+
7+
Stats:
8+
Runtime: 240 ms, faster than 16.60% of Python online submissions for Reverse String.
9+
Memory Usage: 19.6 MB, less than 66.41% of Python online submissions for Reverse String.
10+
11+
Cool resource linked: http://pythontutor.com/live.html#mode=edit
12+
"""
13+
class Solution(object):
14+
def reverseString(self, s):
15+
"""
16+
:type s: List[str]
17+
:rtype: None Do not return anything, modify s in-place instead.
18+
"""
19+
l, r = 0, len(s) - 1
20+
while l < r:
21+
s[l], s[r] = s[r], s[l]
22+
l += 1
23+
r -= 1
24+
return s

0 commit comments

Comments
 (0)