From e056b485e566861ddebdb76e750aac5574dd4d7b Mon Sep 17 00:00:00 2001 From: Mistivia Date: Thu, 1 Feb 2024 20:46:19 +0800 Subject: solve leetcode 1 --- leetcode/1-two-sum/solution.rkt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 leetcode/1-two-sum/solution.rkt 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)) -- cgit v1.0