CodingTest/Leetcode
[LeetCode] 2441. Largest Positive Integer That Exists With Its Negative
Jay_J
2024. 8. 2. 02:34
문제 :
- 처음 보자마자 특정 자료구조가 생각나지는 않았다. 단순 배열 manipulation 문제로만 생각을 했었다.
- 하지만 딕셔너리를 이용하면 좀 더 쉽게 풀 수 있을것 같았다.
class Solution:
def findMaxK(self, nums: List[int]) -> int:
num_dict = {}
max_k = -1
for i in nums:
num_dict[i] = True
if -i in num_dict:
max_k = max(max_k, abs(i))
return max_k
-먼저, 딕셔너리를 선언하고, max_k를 -1로 초기화 해준다.
- 다음으로 nums 리스트를 순회하며 키 값으로는 현재 탐색중인 nums의 요소값, value 값으로는 True를 넣어준다. 사실 여기서의 True는 존재를 확인하기 위한 더미 값일뿐, 그 뒤로는 영향을 주지 않는다.