Using a dictionary or collections.Counter

Jimmy (xiaoke) Shen
1 min readJan 3, 2020

--

846. Hand of Straights

https://leetcode.com/problems/hand-of-straights/

class Solution:
def isNStraightHand(self, hand: List[int], W: int) -> bool:
if len(hand) % W!=0:return False
rounds = len(hand) //W
cnt = collections.Counter(hand)
while rounds>0:
min_x = min(cnt.keys())
this_v = cnt[min_x]
for i in range(W):
if cnt[min_x + i]<this_v:
return False
cnt[min_x + i] -= this_v
if cnt[min_x + i] ==0:
del cnt[min_x+i]
rounds -= this_v
return True

825. Friends Of Appropriate Ages

https://leetcode.com/contest/weekly-contest-82/problems/friends-of-appropriate-ages/

https://leetcode.com/problems/friends-of-appropriate-ages/discuss/127029/C++JavaPython-Easy-and-Straight-Forward

class Solution:
def numFriendRequests(self, ages: List[int]) -> int:
def request(a, b):
return not (b<=0.5*a+7 or b>a or (b>100 and a<100))
cnt = collections.Counter(ages)
res = sum(cnt[a]*cnt[b] for a,b in itertools.permutations(cnt.keys(), 2) if request(a,b))
res += sum(cnt[a]*(cnt[a]-1) for a in cnt if request(a,a))
return res

--

--

No responses yet