-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path611 Valid Triangle Number.py
99 lines (86 loc) · 2.39 KB
/
611 Valid Triangle Number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/python3
"""
Given an array consists of non-negative integers, your task is to count the
number of triplets chosen from the array that can make triangles if we take them
as side lengths of a triangle.
Example 1:
Input: [2,2,3,4]
Output: 3
Explanation:
Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
Note:
The length of the given array won't exceed 1000.
The integers in the given array are in the range of [0, 1000].
"""
from typing import List
class Solution:
def triangleNumber(self, nums: List[int]) -> int:
"""
b - a < c < a + b
Brute force O(n^3)
3 sums
Three-pointers
O(n^2)
"""
ret = 0
nums.sort()
n = len(nums)
for k in range(n-1, 1, -1):
i = 0
j = k - 1
while i < j:
if nums[i] + nums[j] > nums[k]:
ret += j - i # move i will always satisfy the constraint
j -= 1 # to break
else:
i += 1 # to satisfy
return ret
def triangleNumber_error(self, nums: List[int]) -> int:
"""
b - a < c < a + b
Brute force O(n^3)
3 sums
Three-pointers
O(n^2)
"""
ret = 0
nums.sort()
n = len(nums)
for i in range(n - 2):
j = i + 1
k = n - 1
while j < k:
# error, since move k will not break the formula
if nums[i] + nums[j] > nums[k]:
ret += k - j
k -= 1
else:
j += 1
return ret
def triangleNumber_slow(self, nums: List[int]) -> int:
"""
b - a < c < a + b
Brute force O(n^3)
Cache + Prune
"""
cache = {}
nums.sort()
n = len(nums)
ret = 0
for i in range(n):
for j in range(i + 1, n):
if (i, j) not in cache:
cur = 0
for k in range(j + 1, n):
if nums[k] < nums[i] + nums[j]:
cur += 1
else:
break
cache[(i, j)] = cur
ret += cache[(i, j)]
return ret
if __name__ == "__main__":
assert Solution().triangleNumber([2,2,3,4]) == 3