Re: [閒聊] 每日leetcode已回收
看板Marginalman作者sustainer123 (caster )時間1年前 (2024/05/02 10:27)推噓3(3推 0噓 2→)留言5則, 4人參與討論串175/1548 (看更多)
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
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.119.235.6 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1714616822.A.57D.html
推
05/02 10:40,
1年前
, 1F
05/02 10:40, 1F
推
05/02 10:43,
1年前
, 2F
05/02 10:43, 2F
→
05/02 10:43,
1年前
, 3F
05/02 10:43, 3F
→
05/02 10:44,
1年前
, 4F
05/02 10:44, 4F
推
05/02 10:52,
1年前
, 5F
05/02 10:52, 5F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 175 之 1548 篇):