gpt4 book ai didi

javascript - 在元素数组中查找重复的元素系列

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:48:42 27 4
gpt4 key购买 nike

我有一个这样的数组

 var randomArray = [1,2,1,1,1,1,0,2,1,2,3,10,12,54,10,12] etc..

我可以删除重复元素或在其中找到重复元素。但我想记录数组中重复的所有重复元素序列。这是我试过的代码,但它会陷入无限循环

  for (i = 0; i < randomLength; i++) {
var cycle = [i],
flag = 0,
start = i;
for (var j = i + 1; j < randomLength; j++) {
if (randomArray[i] == randomArray[j]) {
cycle.push(randomArray[j]);
while (i <= j) {
if (randomArray[i + 1] == randomArray[j + 1]) {
cycle.push(randomArray[j + 1]);
}
i = i + 1;
j = j + 1;
}
console.log(cycle);
}
i = start;
}
i = start;
}

它应该返回我。我不想用正则表达式做同样的事情

1,2
1,1
10,12

If array is ["a","d","z","e","g","h","a","d","z"]

然后

output would be "a","d","z"

而且应该是最优解。请就此建议我。至少更正我当前的代码..

最佳答案

我使用了“trie”树数据结构(用谷歌搜索了解更多信息)。每个序列的树分支。它找到 1,1,1 作为解决方案,因为 1,1,1 出现了两次。 (如果你想阻止一个数字在两个序列中重复,你需要计算 trie 的每个节点的唯一索引)。

这是代码:运行时间应该是 O(N^2) 之类的,可以稍微改进一下。

var randomArray = [1,2,1,1,1,1,0,2,1,2,3,10,12,54,10,12]

var solve = function(a) {
var trie = {};
var sequence_set = {};
for (var start = 0; start < a.length - 1; start += 1) {
var sub_trie = trie[a[start]] || {};
trie[a[start]] = sub_trie;
sequence = "" + a[start]
for (var i = start + 1; i < a.length; i += 1) {
sequence += "," + a[i]
sub_trie[a[i]] = sub_trie[a[i]] || {};
sub_trie = sub_trie[a[i]];
var sub_trie_count = sub_trie.count || 0;
sub_trie.count = sub_trie_count + 1;
if (sub_trie_count >= 1) {
sequence_set[sequence] = "found";
console.log(sequence);
}
}
}
solution = "";
for (sequence in sequence_set) {
solution += sequence + ", ";
}
console.log(trie)
return solution;
}

输出:

1,1 fiddle.jshell.net:37
1,1,1 fiddle.jshell.net:37
1,1 fiddle.jshell.net:37
2,1 fiddle.jshell.net:37
1,2 fiddle.jshell.net:37
10,12 fiddle.jshell.net:37
Object {0: Object, 1: Object, 2: Object, 3: Object, 10: Object, 12: Object, 54: Object}
fiddle.jshell.net:45

关于javascript - 在元素数组中查找重复的元素系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14795340/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com