1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- (import
- (scheme base)
- (scheme write)
- (srfi 69))
- (define (slow-solution nums target)
- (define sz (vector-length nums))
- (define table (make-hash-table eqv?))
- (let loop ((i 0)
- (j 0))
- (cond
- ((and (< i sz) (< j sz))
- (if (and
- (not (= i j))
- (= (+ (vector-ref nums i)
- (vector-ref nums j))
- target))
- (vector i j)
- (loop i (+ j 1))))
- ((< i sz)
- (loop (+ i 1) 0))
- (else
- #f))))
- (define (fast-solution nums target)
- (define sz (vector-length nums))
- (define table (make-hash-table eqv?))
- (define (check-table i)
- (hash-table-ref/default table
- (- target
- (vector-ref nums i))
- #f))
- (let loop ((i 0))
- (when (< i sz)
- (hash-table-set! table (vector-ref nums i) i)
- (loop (+ i 1))))
- (let loop ((i 0))
- (cond
- ((< i sz)
- (let ((r (check-table i)))
- (if (and r (not (= r i)))
- (vector i r)
- (loop (+ i 1)))))
- (else
- #f))))
- (define (two-sum nums target)
- (fast-solution nums target))
|