在 Python 中找到大於給定目標成對的數字和最小的程式


假設我們有一個名為 nums 的數字列表和另一個值 target。我們必須找到大於目標值的數字對的最小和。

因此,如果輸入為 nums = [2, 4, 6, 10, 14] target = 10,則輸出將為 12,因為我們選擇 2 和 10

為解決此問題,我們將遵循以下步驟 -

  • 對列表 nums 進行排序
  • n := nums 的大小
  • answer := 10^10
  • i := 0, j := n - 1
  • while i < j, 執行下列操作
    • if nums[i] + nums[j] > target, 則
      • answer := answer 和 (nums[i] + nums[j]) 的最小值
      • j := j - 1
    • 否則,
      • i := i + 1
  • 返回 answer

讓我們看看以下實現,以獲得更好的理解 -

示例

 現場演示

class Solution:
   def solve(self, nums, target): nums.sort()
      n = len(nums)
      answer = 10 ** 10
      i, j = 0, n - 1
      while i < j:
         if nums[i] + nums[j] > target:
            answer = min(answer, nums[i] + nums[j])
            j -= 1
         else:
            i += 1
      return answer
ob = Solution()
nums = [2, 4, 6, 10, 14]
target = 10
print(ob.solve(nums, target))

輸入

[2, 4, 6, 10, 14], 10

輸出

12

更新於: 20-11-2020

205 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告