给定一个矩阵ArrayList<Integer>
,我经常在我的代码中写
int val = 2;
for(int i = 0 ; i < N ;i++){
if(matrix[i][0].list.contains(val))
matrix[i][0].remove(val);
}
Run Code Online (Sandbox Code Playgroud)
由于这两个.contains()
和.remove()
在运行O(n)
的时候,它让我想知道如果存在这两个语句相结合的方法,或许,从而提高运行时的效率不知何故?我在几天内对此进行了足够的研究,但找不到令人信服的答案。
给定一个从列表中删除连续重复项的函数
let rec compress l =
match l with
| [] -> []
| [x] -> [x]
| x :: (y :: _ as t) -> if x = y then compress t else x :: compress t;;
Run Code Online (Sandbox Code Playgroud)
产生正确的结果
compress ["a"; "a";"b";"c";"c"] ;;
- : string list = ["a"; "b"; "c"]
Run Code Online (Sandbox Code Playgroud)
但如果x :: (y :: _ as t)
我改为x :: (y :: t)
,那么我会得到不正确的结果
compress ["a"; "a";"b";"c";"c"] ;;
- : string list = ["b"; "c"]
Run Code Online (Sandbox Code Playgroud)
这里发生了什么 ?我无法理解声明如何_ …
我正在练习尾递归,并且考虑到类型
type 'a tree = Leaf of 'a | Pair of 'a tree * 'a tree
Run Code Online (Sandbox Code Playgroud)
以及一个查找二叉树中最大元素的函数
let rec tree_max t = match t with
| Leaf v -> v
| Pair (l,r) -> max (tree_max l) (tree_max r)
Run Code Online (Sandbox Code Playgroud)
使上述函数尾递归
我努力了
let rec tree_max t acc= match t with
| Leaf v -> acc
| Pair (l,r) -> (max (tree_max l) (tree_max r))::ACC
Run Code Online (Sandbox Code Playgroud)
我也尝试过
let rec tree_max t acc= match t with
| Leaf v -> acc
| Pair (l,r) …
Run Code Online (Sandbox Code Playgroud)