solution.scm 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. (import
  2. (scheme base)
  3. (scheme write)
  4. (srfi 69))
  5. (define (slow-solution nums target)
  6. (define sz (vector-length nums))
  7. (define table (make-hash-table eqv?))
  8. (let loop ((i 0)
  9. (j 0))
  10. (cond
  11. ((and (< i sz) (< j sz))
  12. (if (and
  13. (not (= i j))
  14. (= (+ (vector-ref nums i)
  15. (vector-ref nums j))
  16. target))
  17. (vector i j)
  18. (loop i (+ j 1))))
  19. ((< i sz)
  20. (loop (+ i 1) 0))
  21. (else
  22. #f))))
  23. (define (fast-solution nums target)
  24. (define sz (vector-length nums))
  25. (define table (make-hash-table eqv?))
  26. (define (check-table i)
  27. (hash-table-ref/default table
  28. (- target
  29. (vector-ref nums i))
  30. #f))
  31. (let loop ((i 0))
  32. (when (< i sz)
  33. (hash-table-set! table (vector-ref nums i) i)
  34. (loop (+ i 1))))
  35. (let loop ((i 0))
  36. (cond
  37. ((< i sz)
  38. (let ((r (check-table i)))
  39. (if (and r (not (= r i)))
  40. (vector i r)
  41. (loop (+ i 1)))))
  42. (else
  43. #f))))
  44. (define (two-sum nums target)
  45. (fast-solution nums target))