我试图在此处找到可以用一组数字形成的可能三角形的数量:
https://www.geeksforgeeks.org/find-number-of-triangles-possible/
我已经编写了它的javaScript版本。但是,我不太了解解决方案的一部分:
// Total number of possible triangles that can
// be formed with the two fixed elements is
// k - j - 1. The two fixed elements are arr[i]
// and arr[j]. All elements between arr[j+1]/ to
// arr[k-1] can form a triangle with arr[i] and arr[j].
// One is subtracted from k because k is incremented
// one extra in above while loop.
// k will always be greater than j. If j becomes equal
// to k, then above loop will increment k, because arr[k]
// + arr[i] is always greater than arr[k]
问题:
我仍然不明白这个逻辑。 k-j
是如何出现在图片中的?
如何用arr [i],arr [j]和arr [k](使用arr [i]
有人可以启发我吗?
该问题的JS解决方案:
var triangleNumber = function(arr) {
let count = 0, n = arr.length;
//Sort the array in ascending order.
arr.sort((a,b) => { return a-b; });
// Set three pointers, i, j = i+1 and k=i+2
for(let i=0; i<n-2; i++) {
let k = i+2;
for(let j=i+1; j<n; j++) {
// If sum of two sides > third side
/* Find the rightmost element which is smaller
than the sum of two fixed elements
The important thing to note here is, we use
the previous value of k. If value of arr[i] +
arr[j-1] was greater than arr[k], then arr[i] +
arr[j] must be greater than k, because the
array is sorted. */
while (k <n && arr[i] + arr[j] > arr[k]) {
++k;
}
/* Total number of possible triangles that can be
formed with the two fixed elements is k - j - 1.
The two fixed elements are arr[i] and arr[j]. All
elements between arr[j+1] to arr[k-1] can form a
triangle with arr[i] and arr[j]. One is subtracted
from k because k is incremented one extra in above
while loop. k will always be greater than j. If j
becomes equal to k, then above loop will increment
k, because arr[k] + arr[i] is always/ greater than
arr[k] */
count += k-j-1;
}
}
return count<0? 0: count;
};
const arr = [2,2,3,4];
console.log(triangleNumber(arr));
答案 0 :(得分:1)
从k-j
之后的元素到元素j
有k
个元素。它们都是三角形的有效第三边,arr[i]
和arr[j]
是前两个边。
例如如果前两个边分别是arr[2]
和arr[4]
,最高k
,其中arr[i] + arr[j] > arr[k]
是10
,则可以用k = 5, 6, 7, 8, 9, or 10
制作一个三角形。那里有6个索引,还有10 - 4 = 6
。