Re: [闲聊] 每日leetcode

楼主: sustainer123 (caster)   2024-05-02 10:27:00
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
作者: digua (地瓜)   2024-05-02 10:40:00
大师
作者: wu10200512 (廷廷)   2024-05-02 10:43:00
可以用unorder_map 这样不用sort 可以O(N)吗
楼主: sustainer123 (caster)   2024-05-02 10:44:00
听起来可以 让我想一想
作者: DJYOSHITAKA (Evans)   2024-05-02 10:52:00
别卷了

Links booklink

Contact Us: admin [ a t ] ucptt.com