diff options
| author | Mistivia <i@mistivia.com> | 2024-02-01 20:46:19 +0800 |
|---|---|---|
| committer | Mistivia <i@mistivia.com> | 2024-02-01 20:46:19 +0800 |
| commit | e056b485e566861ddebdb76e750aac5574dd4d7b (patch) | |
| tree | 72b5636797ec92553f737989669021ac177794b2 /leetcode/1-two-sum | |
| parent | 836d657d12dbb5a32a3780e4a056a3f46341d41f (diff) | |
solve leetcode 1
Diffstat (limited to 'leetcode/1-two-sum')
| -rw-r--r-- | leetcode/1-two-sum/solution.rkt | 16 |
1 files changed, 16 insertions, 0 deletions
diff --git a/leetcode/1-two-sum/solution.rkt b/leetcode/1-two-sum/solution.rkt new file mode 100644 index 0000000..e155160 --- /dev/null +++ b/leetcode/1-two-sum/solution.rkt @@ -0,0 +1,16 @@ +#lang racket + +;; https://leetcode.com/problems/two-sum/description/ + +(define/contract (two-sum nums target) + (-> (listof exact-integer?) exact-integer? (listof exact-integer?)) + (define h (make-hash)) + (define (loop nums index) + (define n (car nums)) + (define diff (- target n)) + (if (hash-has-key? h diff) + (list index (hash-ref h diff)) + (let () + (hash-set! h n index) + (loop (cdr nums) (+ 1 index))))) + (loop nums 0)) |
