[英]Find if sum of two numbers in an array is equal to k
我正在嘗試解決:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
這是我的解決方案:
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash_table = {}
k = target
for i, x in enumerate(nums):
if x not in hash_table:
hash_table[x] = i
for x in nums:
if k-x in hash_table:
if hash_table[k-x]!= hash_table[x]:
return [hash_table[x], hash_table[k-x]]
現在解決方案不正確,因為它沒有通過像 [3,3], 6 這樣的測試用例。現在兩個 3 都作為預期的一個條目存儲在哈希表中,因此哈希表中只記錄了一個索引 3 和我的解決方案不起作用。
所以,我認為解決方案可能不是哈希表。 但正確的解決方案是:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
現在,這在 Java 中基本上是相同的解決方案,並且它被稱為正確的解決方案。
所以,我的問題是:
謝謝你的幫助。
Java 解決方案有一個檢查兩個相等的元素:
if (map.containsKey(complement) && map.get(complement) != i)
此條件的第一部分 - map.containsKey(complement)
- 表示complement
存在於Map
中,而第二部分 - map.get(complement) != i)
- 表示complement
的索引存儲在map 與索引i
不同。 這意味着如果complement == nums[i]
,則輸入數組中有兩個相同的數字。
我不知道 Python,但看起來你的代碼失敗了,因為
if hash_table[k-x]!= hash_table[x]
當kx == x
時總是返回 false。 您需要將hash_table[kx]
與輸入數組的當前索引進行比較。
根據您的第一個 Python 循環,我假設第二個循環應如下所示:
for i, x in enumerate(nums):
if k-x in hash_table:
if hash_table[k-x]!= i:
return [i, hash_table[k-x]]
為什么不使用簡單的東西:
def twoSum(nums, target):
for i, num1 in enumerate(nums):
for j, num2 in enumerate(nums):
if num1 + num2 == target and i != j:
return [i, j]
return [-1, -1] # or whaterver you want to say "no solution found"
這會產生:
print twoSum([2, 7, 11, 15], 9) # =>[0, 1] 2+7
print twoSum([2, 7, 11, 15], 22) # =>[1, 3] 7+15
print twoSum([2, 7, 11, 15], 23) # => [-1, -1] no solution
作為哈希表解決方案的替代方案,您可以
O(N Log N)
),i
, j
使得num[i] + num[j] <= sum < num[i] + num[j+1]
; 每次增加i
時,都會將j
減少0
或更多以進行調整。 i
從0
開始, j
從末尾開始。 更糟糕的是,對於總共O(N)
次操作,您會增加i
N
次並減少j
N
次。 在平等的情況下,你就完成了。
這可以就地完成。
嘗試使用 JavaScript,
let qarr = [2, 3, 5, 6, 7, 9, 21, 24, 27, 35, 50, 98] //sorted Array const qk = 85 function check_sum(arr, k){ for( i in arr){ if(arr[i]+arr[arr.length-1] === k){ return [qarr.indexOf(arr[i]), qarr.indexOf(arr[arr.length-1])] } else{ if(arr[i]+arr[arr.length-1] >= k){ if(arr.length == 2){ return arr[0]+arr[1] == k ? [qarr.indexOf(arr[0], qarr.indexOf(arr[1]))] : [null, null] } else if(arr.length == 1){ return arr[0]*2 == k ? [qarr.indexOf(arr[0]), qarr.indexOf(arr[0])] : [null, null] } else{ return check_sum(arr.slice(i), k) } } } } } res = check_sum(qarr.filter(a=> a<=qk), qk) console.log('result', res)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.