sicp每日一題[2.62]

再思即可發表於2024-10-30

Exercise 2.62

Give a (n) implementation of union-set for sets represented as ordered lists.


這道題難度也不大,思路是依次從兩個集合中取第一個元素,比較他們的大小,把小的那個和剩下所有元素連線的結果連線起來。由於兩個集合中每個元素都只需要取出一次,所以時間複雜度應該是 O(n)。

(define (union-set set1 set2)
  (cond ((null? set1) set2)
        ((null? set2) set1)
        ((let ((s1 (car set1))
               (s2 (car set2)))
           (if (<= s1 s2)
               (cons s1 (union-set (cdr set1) set2))
               (cons s2 (union-set set1 (cdr set2))))))))

(define set1 (list 1 3 5 7 9))
(define set2 (list 2 4 6 8 10))

(union-set set1 set2)

; 結果如下所示
'(1 2 3 4 5 6 7 8 9 10)

相關文章