일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Medium
- Union Find
- dfs
- Bellman-Ford
- Java
- DailyLeetCoding
- stack
- hash table
- array
- LinkedList
- BFS
- VCS
- graph
- Hashtable
- Leedcode
- Easy
- SinglyLinkedList
- ArrayList vs LinkedList
- String
- A* Algorithm
- Two Pointers
- greedy
- hash
- heap
- 자료구조
- 광연자동차운전면허학원
- sorting
- 구현
- python3
- leetcode
Archives
- Today
- Total
Min IT's Devlog
[python3] 1996. The Number of Weak Characters in the Game 본문
코테/LeetCode(Solve)
[python3] 1996. The Number of Weak Characters in the Game
egovici 2022. 9. 9. 16:33풀이 일자: 22.09.09
난이도: [Medium]
분류: [Greedy, Sorting]
문제 내용
주어진 character 집합에서 상대적으로 ATK, DEF가 다른 character보다 낮은 경우 Weak라고 하며 Weak character의 수를 찾는 문제.
문제 해결 흐름
1. 다른 ATK, DEF보다 낮은 player의 수를 찾아야 하니까 뭔가 극단적인 값을 이용하면 되지 않을까?
→ Greedy하게 현재 주어진 배열에서 ATK와 DEF가 상대적으로 가장 높은 값을 가지고 시작하자.
2. 가장 높은 값을 가지고 시작하되 좀 더 쉽게 만드는 방법이 있을까?
→ 배열이 ATK 내림차순, DEF 오름차순으로 정렬하면 비교하는데 크게 문제가 없겠다.
class Solution:
def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
ans = 0
properties.sort(key= lambda x : (-x[0],x[1]))
maxATK, maxDEF = 0 , 0
for ATK, DEF in properties:
if (ATK < maxATK) and (DEF < maxDEF):
ans += 1
elif DEF > maxDEF:
maxATK = ATK
maxDEF = DEF
else:
pass
return ans
→ 현재 여기에서 sort하는 과정이 시간이 많이 걸리는 것으로 판단하여 sort기준을 줄이고 추가적인 변수를 설정하여 기준을 줄인 것에 대한 보조적인 코드를 추가하였다. 시간은 조금 줄었으나 크게 줄지 않았다.
다른 해결 방식
→ 큰 차이는 없었으나 Runtime 속도가 빠른 코드의 경우 for문에서 in으로 뽑아오는 코드가 아니라 length를 이용해 for을 돌리고 index로 접근하였다.
class Solution:
def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
properties.sort(key=lambda x:(-x[0],x[1])) #check the x[0] if they are same then check the x[1]
mxattack=properties[0][0]
mxdefense=properties[0][1]
count=0
for i in range(1,len(properties)):
if properties[i][0]<mxattack and properties[i][1]<mxdefense:
count+=1
else:
mxattack=properties[i][0]
mxdefense=properties[i][1]
return count
문제 링크
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/
'코테 > LeetCode(Solve)' 카테고리의 다른 글
[python3] 1626. Best Team With No Conflicts (0) | 2023.02.03 |
---|---|
[python3] 1328. Break a Palindrome (0) | 2022.10.11 |
[python3] 429. N-ary Tree Level Order Traversal (0) | 2022.09.05 |
[python3] 987. Vertical Order Traversal of a Binary Tree (0) | 2022.09.04 |
[python3] 967. Numbers With Same Consecutive Differences (0) | 2022.09.03 |
Comments