原文連接git
給定一個整數數組和一個目標值,找出數組中和爲目標值的兩個數。github
你能夠假設每一個輸入只對應一種答案,且一樣的元素不能被重複利用。數組
示例:markdown
給定 nums = [2, 7, 11, 15], target = 9網絡
由於 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]oop
來源:力扣(LeetCode) 連接:leetcode-cn.com/problems/tw… 著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。post
func TwoSum(nums []int, target int) []int { m := map[int]int{} for i1, n1 := range nums { n2 := target - n1 i2, ok := m[n2] if ok { return []int{i2, i1} } m[n1] = i1 } return nil } 複製代碼
遞歸spa
(defun two-sum (lst tar) (two-sum-helper lst tar 0 (find-num-index (cdr lst) (- tar (car lst)) 1))) (defun two-sum-helper (lst tar m n) (if (null lst) nil (if (numberp n) (list m n) (two-sum-helper (cdr lst) tar (+ m 1) (find-num-index (cdr lst) (- tar (car lst)) (+ m 2)))))) (defun find-num-index(lst tar n) (if (null lst) nil (if (eql tar (car lst)) n (find-num-index (cdr lst) tar (+ n 1))))) 複製代碼
非遞歸code
(defun two-sum (lst tar) (let ((ht (make-hash-table)) (l (length lst)) (n nil)) (do ((i 0 (+ i 1))) ((> i l) nil) (setf n (gethash (- tar (car lst)) ht)) (if (numberp n) (return-from two-sum (list n i))) (setf (gethash (car lst) ht) i) (pop lst)))) 複製代碼