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