小编hex*_*ark的帖子

Java结合ArrayList contains()和ArrayList remove()

给定一个矩阵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)的时候,它让我想知道如果存在这两个语句相结合的方法,或许,从而提高运行时的效率不知何故?我在几天内对此进行了足够的研究,但找不到令人信服的答案。

java arraylist

3
推荐指数
1
解决办法
65
查看次数

模式匹配中“as”的范围

给定一个从列表中删除连续重复项的函数

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)

这里发生了什么 ?我无法理解声明如何_ …

ocaml pattern-matching

2
推荐指数
1
解决办法
63
查看次数

OCaml 中二叉树的尾递归最大元素

我正在练习尾递归,并且考虑到类型

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)

ocaml

1
推荐指数
1
解决办法
1139
查看次数

标签 统计

ocaml ×2

arraylist ×1

java ×1

pattern-matching ×1