有一个数组:[1,1,1,1,2,3,4],计算数组中所有相同差值的集合 ※数组中每个集合的差值不能相同
Way to count one set have same difference:
-1,0,1 -> count = 1 with diff = 1
1,1,1 -> count = 1 with diff = 0
1,2,3,4 -> count = 3 with diff = 1 ([1,2,3],[1,2,3,4],[2,3,4])
0,1 -> not count
0,1,3 -> not count
0,1,1,2 -> not count , althought it has 0,1 and 1,2 with diff = 1 but it is not continous
As the above array [1,1,1,1,2,3,4] count = 6
There are 6 sets has the same difference value:
[1,1,1],[1,1,1,1],[1,1,1] with difference = 0
[1,2,3],[1,2,3,4],[2,3,4] with difference = 1
这是我的暴力手段O(n2) 我可以结合使用DP来更有效地改善它吗?
function run(pArray){
var count = 0;
var length = pArray.length;
for(var i = 0;i<length - 2;i++){
var nextIdx = i + 1;
var diff = pArray[nextIdx]-pArray[i];
while(true){
nextIdx ++;
if(nextIdx > length - 1){
break;
}
if(pArray[nextIdx] - pArray[nextIdx - 1] !== diff){
break;
}else{
count ++;
}
}
}
console.log(count);
}
run([1,1,1,1,2,3,4]);
答案 0 :(得分:0)
根据您的最新评论,似乎您确实关心数组中元素的顺序。因此,不需要对其进行排序,在那种情况下,集合的数量可以像[1,2,1,2,1]那样评估为零。
在这种情况下,可以在O(n)
中完成。
想法是:
如果找到匹配的差异,则递增一个计数变量,更新 结果作为结果=结果+计数。
举个例子[1,1,1,1]。您无需考虑索引0,1。
采用索引2来查看arr [2]-arr [1] == arr [1]-arr [0],然后递增 从0到1计数,然后将其添加到结果中。
采用索引3来查看arr [3]-arr [2] == arr [2]-arr [1],是的 等于,然后将count增加到2,将其相加。现在结果= 1 + 2 = 3。
只要您知道满足以下条件的元素,您就会知道 条件arr [i]-arr [i-1] == arr [i-1]-arr [i-2]您不断添加 下一个更高的值。因此结果= 1 + 2 + 3 + .... i-2依此类推 给定索引i
如果找不到匹配的差异,请将计数变量重置为零 然后重新开始。
注意:我不太熟悉Javascript,但是看起来像这样:
<div>
<script>
function countSets(arr) {
if (arr === undefined || arr.length < 3) return 0;
let count = 0;
let res = 0;
for (let i = 2; i < arr.length; ++i) {
if (arr[i] - arr[i - 1] === arr[i - 1] - arr[i - 2]) {
count++;
} else {
count = 0;
}
res += count;
}
return res;
}
console.log("[1, 1, 1] -> " + countSets([1, 1, 1]))
console.log("[1, 1, 1, 2, 2, 2] -> " + countSets([1, 1, 1, 2, 2, 2]))
console.log("[1, 1, 1, 2, 3, 4] -> " + countSets([1, 1, 1, 2, 3, 4]))
console.log("[1, 1, 2, 3, 4, 4, 5, 5] -> " + countSets([1, 1, 2, 3, 4, 4, 5, 5]))
console.log("[1, 1, 1, 2, 3, 4, 5, 6] -> " + countSets([1, 1, 1, 2, 3, 4, 5, 6]))
console.log("[1, 2, 1, 2, 1] -> " + countSets([1, 2, 1, 2, 1]))
</script>
</div>