精華區beta Marginalman 關於我們 聯絡資訊
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
digua: 大師 05/02 10:40
wu10200512: 可以用unorder_map 這樣不用sort 可以O(N) 05/02 10:43
wu10200512: 嗎 05/02 10:43
sustainer123: 聽起來可以 讓我想一想 05/02 10:44
DJYOSHITAKA: 別捲了 05/02 10:52