everycode
everycode copied to clipboard
2014年11月25日
根据传入的3个参数(边长)number,返回一个数值number代表三角形的类型。
提示:可以先算出这个三角形的3个角,然后做比较。
/* 返回 ᐃ 的类型:
0 : 如果不能构成一个ᐃ
1 : 锐角ᐃ
2 : 正角 ᐃ
3 : 钝角 ᐃ
*/
function triangleType(a, b, c){
return 0;
}
triangleType(2, 4, 6); // return 0 (Not triangle)
triangleType(8, 5, 7); // return 1 (Acute, angles are approx. 82°, 38° and 60°)
triangleType(3, 4, 5); // return 2 (Right, angles are approx. 37°, 53° and exactly 90°)
triangleType(7, 12, 8); // return 3 (Obtuse, angles are approx. 34°, 106° and 40°)
function triangleType(a, b, c) {
return [ [ a, b, c], [ b, c, a], [ c, a, b] ].reduce(function(type, cond) {
return !type ?
type :
(cond[0] + cond[1] <= cond[2] ?
0 :
(Math.max(type, ((cond[0] * cond[0] + cond[1] * cond[1]) === cond[2] * cond[2] ?
2 :
((cond[0] * cond[0] + cond[1] * cond[1] < cond[2] * cond[2]) ? 3 : 1)))));
}, 1);
}
function triangleType(a, b, c){
var max = Math.max(a, b, c);
if(max >= (a + b + c - max)) //两边之和小于等于第三边
return 0;
var result = max*max - (a*a + b*b + c*c - max*max);//最长边的平方减去其余两边平方和
if(result > 0) {
return 3;
} else if(result < 0){
return 1;
} else {
return 2;
}
}
console.log(triangleType(2, 4, 6));//0
console.log(triangleType(8, 5, 7));//1
console.log(triangleType(3, 4, 5));//2
console.log(triangleType(7, 12, 18));//3
再来一个,参考了 @businiaowa 的
function triangleType(a, b, c) {
return [[a, b, c].sort(function(a, b) {return a - b;})].reduce(function(r, arr) {
return arr.push(arr[0] * arr[0] + arr[1] * arr[1]),
arr.push(arr[2] * arr[2]),
(arr[0] + arr[1] <= arr[2]) ?
0 :
(arr[3] === arr[4] ?
2 :
arr[3] < arr[4] ? 3 : 1);
}, 0);
}
@XadillaX 大神,有人问我回文判断的算法,而且要时间复杂度最小,怎么实现? var s1= "reaer"; var s2="reaaer";
@Jonavin ~~递 Manacher 算法不谢。~~
看错需求了,我看成要找到最大的回文子串了。
就判断回文么直接两头 for 过来一一对比到中间过不就好了。