clojure实现最长上升子序队列算法
2014-10-18 08:47
169 查看
4Clojure上的一道题:4Clojure 最长上升子序列算法
描述如下:
Given a vector of integers, find the longest consecutive sub-sequence of increasing numbers. If two sub-sequences have the same length, use the one that occurs first. An increasing sub-sequence must have a length of 2 or greater to qualify.
例:
[1 0 1 2 3 0 4 5]的最长上升子序列为 [0 1 2 3]
[5 6 1 3 2 7]的最长上升子序列为 [5 6]
另外一种实现:
最终结果:
描述如下:
Given a vector of integers, find the longest consecutive sub-sequence of increasing numbers. If two sub-sequences have the same length, use the one that occurs first. An increasing sub-sequence must have a length of 2 or greater to qualify.
例:
[1 0 1 2 3 0 4 5]的最长上升子序列为 [0 1 2 3]
[5 6 1 3 2 7]的最长上升子序列为 [5 6]
(defn test [coll] ;使用map存放每个起始元素的上升队列,key无意义,仅用于标记不同的队列 (loop [flag 0 tmp-result {flag [(first coll)]} index 0] (if (< index (- (count coll) 1)) (let [current (nth coll index) next (nth coll (inc index))] (if (> next current) ;如果下一个元素大于当前元素,把下一个元素加入到当前元素的队列中,flag就是key,保持不变 (recur flag (assoc tmp-result flag (conj (tmp-result flag) next)) (inc index)) ;否则说明新的队列开始了,新建一个队列,key为flag+1,value为下一个元素 (recur (inc flag) (assoc tmp-result (inc flag) [next]) (inc index)))) ;得到结果之后筛选最长的队列 (let [tmp (vals tmp-result)] (loop [final (first tmp) s (next tmp)] (if (first s) (if (>= (count (first s)) (count final)) (recur (first s) (next s)) (recur final (next s))) ;队列长度至少为2 (if (> (count final) 1) final [])))))))
另外一种实现:
(defn test [coll] (let [pairs (partition 2 1 coll) ; 分组:first与last大小比较 group-pairs (partition-by #(< (first %) (last %)) pairs) ; 保留first大于last的pair filter-pairs (filter #(every? (fn [pair] (< (first pair) (last pair))) %) group-pairs) ; rise-seq (map #(concat (first %) ; 取pair的最后一个数字 (map last (rest %))) filter-pairs) candidate (reverse rise-seq)] (if (empty? candidate) [] (apply (partial max-key count) candidate))))
最终结果:
<!-- lang: vb --> user=> (test [5 6 1 3 2 7]) [5 6] user=> (test [1 0 -1 3 0]) [-1 3] user=> (test [1 0 1 2 3 0 4 5]) [0 1 2 3]
相关文章推荐
- 最长上升子序列问题 nlogn 实现算法的简述
- 最长上升子序列、最长下降子序列的DP算法由O(n^2)到O(nlogn)算法实现及其优化
- 算法基础之python实现动态规划中数字三角形和最长上升子序列问题
- 最长上升子序列(LIS)算法分析
- 实用算法实现-第 8 篇 后缀树和后缀数组 [2 最长公共子串]
- 无向图的最短路径算法(队列实现 )
- 【数据结构与算法基础】以数组实现的循环队列 / Circular Queue implemented by array
- 用VB实现循环队列算法收藏
- 算法笔记(堆实现的最大优先队列)
- C#数据结构和算法学习系列七----队列、队列的实现和应用
- 数据结构和算法设计(迷宫求解问题的栈和队列的实现)
- 实用算法实现-第 8 篇 后缀树和后缀数组 [4 最长回文子串]
- 最长公共上升子序列的另一个O(mn)的算法
- 实用算法实现-第 8 篇 后缀树和后缀数组 [4 最长回文子串]
- 堆-实现优先级队列算法
- 实用算法实现-第 8 篇 后缀树和后缀数组 [2 最长公共子串]
- 逆向最长匹配算法的实现
- LCS 最长公共字串算法实现
- nachos 3.4 实现抢占式多级队列反馈算法
- 实用算法实现-第 8 篇 后缀树和后缀数组 [3 两个字符串的最长公共子串]