ROSALIND|2SUM (2SUM)
給定 k 個長度為 n 的整數數列,求各數列裡互為加法反元素(相反數)的兩數位置。
Given: A positive integer $k \leq 20$, a positive integer $n \leq 10^4$, and $k$ arrays of size $n$ containing integers from $-10^5$ to $10^5$.
Return: For each array $A[1..n]$, output two different indices $1 \leq p < q \leq n$ such that $A[p] = -A[q]$ if they exist, and
"-1"
otherwise.
(https://rosalind.info/problems/2sum/)
數字與其相反數之和為零,例如 1 的相反數為 -1,0 的相反數為 0。此題為經典題目 two sum 的特例,即求出數列裡,和為 0 的兩數位置。
LeetCode 的 Two Sum 規範數列僅有一組解,Rosalind 的題目沒有明示,但從測試資料推論,應該只要求第一組解即可。
這題我以前練習過,算法可參考當時的筆記,以下附上程式碼:
1 | def two_sum(l, target): |