有效三角形的个数
1.直接暴力,先排序然后依次枚举,不满足条件的时候跳出。
时间复杂度o(n^3)
class Solution(object):
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums)
if max(nums)==min(nums)==0:return 0
n = len(nums)
ans = 0
for x in range(n-2):
for y in range(x+1,n-1):
for z in range(y+1,n):
if nums[x]+nums[y]>nums[z]:
ans+=1
else:
break
return ans
2.注意到 这里涉及到在有序表中的查找问题,所以一般优化的思路都是用二分查找。可以将复杂度从n降低到logn 总体的复杂度 为n^2logn
public class Solution {
int binarySearch(int nums[], int l, int r, int x) {
while (r >= l && r < nums.length) {
int mid = (l + r) / 2;
if (nums[mid] >= x)
r = mid - 1;
else
l = mid + 1;
}
return l;
}
public int triangleNumber(int[] nums) {
int count = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int k = i + 2;
for (int j = i + 1; j < nums.length - 1 && nums[i] != 0; j++) {
k = binarySearch(nums, k, nums.length - 1, nums[i] + nums[j]);
count += k - j - 1;
}
}
return count;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/valid-triangle-number/solution/you-xiao-san-jiao-xing-de-ge-shu-by-leetcode/
3.还有o(n^2的算法 等我明天起来在想)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。