[LeetCode] 1395. Count Number of Teams

Updated:

1395. Count Number of Teams

주어진 λ°°μ—΄μ—μ„œ 3 λͺ…을 λ½‘λŠ”λ° λ‹€μŒκ³Ό 같은 쑰건을 만쑱 μ‹œν‚€λ©΄μ„œ λ½‘μœΌλ©΄ λœλ‹€.

index λŠ” i < j < k, 값은 rating[i] < rating[j] < rating[k] or rating[i] > rating[j] > rating[k]

μ΄λ•Œ 뽑을 수 μžˆλŠ” 경우의 수λ₯Ό λͺ¨λ‘ κ΅¬ν•˜λŠ” λ¬Έμ œμ΄λ‹€.

μ²˜μŒμ—” combination 으둜 ν’€μ—ˆλ‹€κ°€ 두 λ²ˆμ§Έλ‘œλŠ” index λ₯Ό 직접 μ ‘κ·Όν•˜μ—¬ ν’€μ—ˆλ‹€.


from typing import List
from itertools import combinations


class Solution:
	def solution1(self, rating: List[int]) -> int:
		answer = 0
		for cur in combinations(rating, 3):
			if cur[0] < cur[1] and cur[1] < cur[2]:
				answer += 1
			elif cur[0] > cur[1] and cur[1] > cur[2]:
				answer += 1

		return answer

	def solution2(self, rating: List[int]) -> int:
		answer = 0
		for i in range(len(rating) - 2):
			for j in range(i + 1, len(rating) - 1):
				for k in range(j + 1, len(rating)):
					if rating[i] > rating[j] > rating[k]:
						answer += 1
					elif rating[i] < rating[j] < rating[k]:
						answer += 1

		return answer

λ¬Έμ œμ—μ„  rating 의 길이가 200 이라 속도 λ©΄μ—μ„œ 차이가 μ—†μ§€λ§Œ 길이가 1000 λ‹¨μœ„λ‘œ λ„˜μ–΄κ°€λ©΄ solution1 이 10초 κ°€λŸ‰ 더 λΉ λ₯΄λ‹€.

κ·Έλž˜λ„ λ‘˜ λ‹€ 길이가 κΈ΄ rating 이 μ˜¨λ‹€λ©΄ μ„±λŠ₯면에선 꽝이닀. combination 을 μ „λΆ€ κ΅¬ν•˜κ³ .. O(n^3) 이고..

κ·Έλž˜μ„œ λ‹€λ₯Έ μ‚¬λžŒλ“€μ˜ O(n^2), O(nlogn) λ³΅μž‘λ„λ₯Ό 가진 μ½”λ“œλ₯Ό λ΄€λŠ”λ° 그곳은 λ‚΄κ°€ 감당할 곳이 μ•„λ‹ˆμ—ˆλ‹€..


Categories:

Updated:

Leave a comment