둘 다 easy~~
A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.
Now, call a "count-paired domain" to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be "9001 discuss.leetcode.com".
We are given a list cpdomains of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
dic = {}
for i in range(len(cpdomains)):
tmp = cpdomains[i].split()
time = int(tmp[0])
if tmp[1] in dic:
dic[tmp[1]] += time
else:
dic[tmp[1]] = time
while "." in tmp[1]:
idx = tmp[1].index(".")
tmp[1] = tmp[1][idx+1:]
if tmp[1] in dic:
dic[tmp[1]] += time
else:
dic[tmp[1]] = time
ans = []
for key, val in dic.items():
tmp = str(val) + " " + key
ans.append(tmp)
return ans
우선 도메인을 split 해서 time 과 domain 분리
time 값은 int 형으로 두고, domain 은 dic
에 넣어줌 (이미 있을 경우 time 만 더하기)
앞쪽의 .
을 기준으로 자른 것도 도메인이므로 도메인[idx+1:]
식으로 잘라서 똑같이 dic
에 update
ans
에 val 값과 key 값을 붙여서 넣어주면 끝~
근데 느리다...
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
ans = collections.Counter()
for domain in cpdomains:
count, domain = domain.split()
count = int(count)
frags = domain.split('.')
for i in range(len(frags)):
ans[".".join(frags[i:])] += count
return ["{} {}".format(ct, dom) for dom, ct in ans.items()]
비슷한데 domain.split('.')
한 후에 ".".join(frags[i:])
이렇게 해도 됨~
"{} {}".format(ct, dom)
=> "count domain" 순서로 저장
루션이도 느리다...^^
In a array nums of size 2 * n, there are n + 1 unique elements, and exactly one of these elements is repeated n times.
Return the element repeated n times.
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
n = len(nums) // 2
count = collections.Counter(nums)
for key, time in count.items():
if time == n:
return key
내 사랑 Counter 써서 n + 1 개의 값이 각각 몇번 등장하는지 구하고
그 중에 n
번 등장하는 값을 찾아서 return key
그냥 반복문 돌려서 count(값) == n
인 것도 해봤는데 훨씬 느림
루션이도 비슷한데 n
과 비교하지 않고 1 보다 크면 무조건 return
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
for k in range(1, 4):
for i in range(len(nums) - k):
if nums[i] == nums[i+k]:
return nums[i]
4 칸 앞까지의 이웃들만 봐도 반복되는지 알 수 있다네요
좀 더 빠르다