| 1트
import collections
def solution(A):
a_length = len(A)
a_hash = collections.defaultdict(int)
lead_num = 0
answer=0
for i, num in enumerate(A):
a_hash[num] += 1
if a_hash[num] > a_length/2:
lead_num = num
break
for i , _ in enumerate(A[:-1]):
if A[:i + 1].count(lead_num) > (i+1) / 2 and A[i+1 : ].count(lead_num) > (a_length - i - 1) / 2:
answer += 1
return answer
결과는 여기에
| 2트
import collections
def solution(A):
a_length = len(A)
a_hash = collections.defaultdict(int)
lead_num = 0
answer=0
for i, num in enumerate(A):
a_hash[num] += 1
if a_hash[num] > a_length/2:
lead_num = num
break
for i , _ in enumerate(A[:-1]):
first_count = 0
is_first = False
for num in A[:i + 1]:
if num == lead_num:
first_count += 1
if first_count > (i + 1) / 2:
is_first = True
if is_first:
second_count = 0
for num in A[i + 1:]:
if num == lead_num:
second_count += 1
if second_count > (a_length - i - 1) / 2:
answer += 1
continue
else:
continue
return answer
결과는 여기에
- 중간에 혹시 반복문을 덜 실행(?) 해보면 괜찮을까 해서 위처럼 짰는데 오히려 더 안 좋아졌다
| 3트
import collections
def solution(A):
a_length = len(A)
a_hash = collections.defaultdict(int)
lead_num = 0
for i, num in enumerate(A):
a_hash[num] += 1
if a_hash[num] > a_length/2:
lead_num = num
answer = 0
count = 0
for i, num in enumerate(A):
if num == lead_num:
count += 1
if count > (i + 1) / 2 and a_hash[lead_num] - count > (a_length - i - 1) /2 :
answer += 1
return answer
- 생각해보니 for문 한번 돌면서 count 계속 갱신하면 해결되는 문제였다
결과는 여기에