[Swift]LeetCode1099. 小於 K 的兩數之和 | Two Sum Less Than K

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-yjvemgtm-kz.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this equation, return -1. git

Example 1:github

Input: A = [34,23,1,24,75,33,54,8], K = 60 Output: 58 Explanation: We can use 34 and 24 to sum 58 which is less than 60. 

Example 2:數組

Input: A = [10,20,30], K = 15 Output: -1 Explanation: In this case it's not possible to get a pair sum less that 15. 

Note:微信

  1. 1 <= A.length <= 100
  2. 1 <= A[i] <= 1000
  3. 1 <= K <= 2000

給你一個整數數組 A 和一個整數 K,請在該數組中找出兩個元素,使它們的和小於 K 但儘量地接近 K,返回這兩個元素的和。less

如不存在這樣的兩個元素,請返回 -1。 this

示例 1:spa

輸入:A = [34,23,1,24,75,33,54,8], K = 60
輸出:58
解釋:
34 和 24 相加獲得 58,58 小於 60,知足題意。

示例 2:code

輸入:A = [10,20,30], K = 15
輸出:-1
解釋:
咱們沒法找到和小於 15 的兩個元素。 

提示:htm

  1. 1 <= A.length <= 100
  2. 1 <= A[i] <= 1000
  3. 1 <= K <= 2000

 36 ms

 1 class Solution {
 2     func twoSumLessThanK(_ A: [Int], _ K: Int) -> Int {
 3         let n:Int = A.count
 4         var ret:Int = -1
 5         for i in 0..<n
 6         {
 7             for j in (i + 1)..<n
 8             {
 9                 if A[i] + A[j] < K
10                 {
11                     ret = max(ret, A[i] + A[j])
12                 }
13             }
14         }
15         return ret
16     }
17 }
相關文章
相關標籤/搜索