题目一
用尽可能多的方法找出数组中重复出现过的元素
例如:[1,2,4,4,3,3,1,5,3] 输出:[1,3,4]
作者补充:若给出多种方式,请分别给出他们的复杂度
<script>
var input = [1,2,4,4,3,3,1,5,3];
var counter = new Array();
var output = new Array();
for(var i = 0; i < input.length; i++) {
if(counter[input[i]]==undefined) counter[input[i]] = 0;
counter[input[i]]++;
}
for(var i = 0; i < counter.length; i++) {
if(counter[i] >= 2) {
output.push(i);
}
}
console.log("counter:",counter.join(','));
console.log("output:", output.join(','));
</script>
</body>
题目二
给定一些文档(docs)、词(words),找出词在文档中全部存在的所有文档
<script type="text/javascript" charset="utf-8">
var docs = [
{
id: 1,
words: ['hello',"world"]
},
{
id: 2,
words: ['hello',"kids"]
},
{
id: 3,
words: ['zzzz',"hello"]
},
{
id: 4,
words: ['world',"kids"]
}
];
findDocList(docs,['hello']) //文档1,文档2,文档3
findDocList(docs,['hello','world']) //文档1
</script>
<script>
var docs = [{id:1, words:['hello', 'world']}, {id:2, words:['hello']}, {id:3, words:['hello', 'vertical']}];
function findDocList(docs, arrKey) {
var target = new Array();
var targetStr = arrKey.join('?');
for(var i = 0; i < docs.length; i++) {
var wordsStr = docs[i].words.join('?');
if(wordsStr.indexOf(targetStr) != -1) {
target.push(docs[i]);
}
}
for(var i = 0; i < target.length; i++) {
var str = "文档";
console.log(str+target[i].id);
}
}
findDocList(docs, ['hello', 'world']);
</script>