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()
cnt = int(tmp[0])
tmp = tmp[1].split(".")
for j in range(len(tmp)):
d = '.'.join(tmp[j:])
if d in dic:
dic[d] += cnt
else:
dic[d] = cnt
ans = []
for k, v in dic.items():
ans.append(str(v)+" "+k)
return ans
우선 숫자와 도메인 분리해서 cnt
에 숫자 값 넣어주기
도메인은 .
단위로 또 분리해서
discuss.leetcode.com
=> leetcode.com
=> com
순으로 dic
에 넣어주기
다시 dic
를 보면서 ans
에 숫자 도메인
형태로 넣어주고 return
파이썬 dictionary
- 아예
collections.Counter()
형으로 선언하면 이 과정 필요 Xif d in dic: dic[d] += cnt else: dic[d] = cnt
- 아니면
get(바꿀 값, default값)
쓰기
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 k, v in count.items():
if v == n:
return k
Counter 로 숫자들의 개수를 세서 n
번 나온 key 값 return
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
n = len(nums) // 2
nums.sort()
for i in range(len(nums)//2+1):
if nums[i] == nums[i+n-1]:
return nums[i]
nums
를 정렬한 후 n
길이 만큼 같은 숫자일 경우 찾기 if nums[i] == nums[i+n-1]:
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
n = []
for i in range(len(nums)):
if nums[i] in n:
return nums[i]
n.append(nums[i])
생각해보니.. 문제 조건으로 unique 한 숫자가 n+1 개 라고 했으므로
답이 되는 숫자 외에는 중복되는 숫자를 가질 수 없음 => 중복 되는 순간 바로 return
n 가지의 숫자들 + n 번 반복되는 숫자 하나 = 2 * n