문제
Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array.
Return the positive integer k. If there is no such integer, return -1.
정수 리스트 nums가 주어졌을 때 음수도 들어있는 양수의 최대값을 찾는 문제이다.
Example 1:
Input: nums = [-1,2,-3,3] Output: 3 Explanation: 3 is the only valid k we can find in the array.
Example 2:
Input: nums = [-1,10,6,7,-7,1] Output: 7 Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.
Example 3:
Input: nums = [-10,8,6,7,-2,-3] Output: -1 Explanation: There is no a single valid k, we return -1.
풀이
아이디어
- 포인터 사용
코드
class Solution:
def findMaxK(self, nums: List[int]) -> int:
p1 = 0
p2 = len(nums)-1
nums.sort()
while p1 < p2:
if -nums[p1] == nums[p2]: return nums[p2]
elif -nums[p1] < nums[p2]: p2 -= 1
else: p1 += 1
if nums[p1] >= 0: break
return -1
후기
포인터를 다룰줄 안다면 쉽게 풀 수 있는 문제였다.