- 算法
贪心,二分查找 - 核心思想
排序完成后,遍历a+b,找出所有符合a+b>c的值。 - 代码
class Solution {
public int triangleNumber(int[] nums) {
if(nums.length < 3) return 0;
Arrays.sort(nums);
int res = 0;
for(int i = 0;i < nums.length;++i){
for(int j = i + 1;j < nums.length;++j){
int left = j+1,right = nums.length - 1,k = j,sum = nums[i]+nums[j];
while(left <= right){
int mid = (right + left)/2;
if(nums[mid] == sum){
right = mid - 1;
}else if(nums[mid] < sum){
left = mid + 1;
k = mid;
}else{
right = mid - 1;
}
}
res += k - j;
}
}
return res;
}
}
|