https://reurl.cc/lQeDQj
2441. Largest Positive Integer That Exists With Its Negative
给定一不包含0的数列,寻找最大正整数,此正整数k的-k需存在于nums
回传正整数k 如果无符合条件的正整数 回传-1
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.
Constraints:
1 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
nums[i] != 0
思路:
排序数列 用two pointer寻找符合条件的正整数
Python Code:
class Solution:
def findMaxK(self, nums: List[int]) -> int:
nums.sort()
print(nums)
start = 0
end = len(nums)-1
while start < end:
if abs(nums[start]) == nums[end] and nums[start] < 0:
return nums[end]
elif abs(nums[start]) > nums[end]:
start += 1
else:
end -= 1
return -1