Skip to content

Commit c17a341

Browse files
排序
1 parent 8c1d65f commit c17a341

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
'''
2+
Descripttion: 三角形的最大周长
3+
version: 1
4+
Author: Jason
5+
Date: 2020-11-29 13:36:03
6+
LastEditors: Jason
7+
LastEditTime: 2020-11-29 14:31:19
8+
'''
9+
from typing import List
10+
import random
11+
12+
13+
def GenerateRandomList(number, size):
14+
temp = list()
15+
random_legth = random.randint(0, size)
16+
current_length = 0
17+
while current_length < random_legth:
18+
temp.append(random.randint(1, number))
19+
current_length += 1
20+
return temp
21+
22+
23+
class Solution:
24+
def largestPerimeter(self, A: List[int]) -> int:
25+
length = len(A)
26+
if length < 3:
27+
return 0
28+
A.sort()
29+
res = 0
30+
# 倒序遍历
31+
for i in range(length - 1, 1, -1):
32+
second = i - 1
33+
third = i - 2
34+
if second > -1 and third > -1:
35+
if A[second] + A[third] <= A[i]:
36+
continue
37+
38+
# if A[i] - A[second] >= A[third] or A[i] - A[third] > A[second] or A[second] - A[third] >= A[i]:
39+
if A[i] - A[third] > A[second]:
40+
continue
41+
42+
temp_sum = A[i] + A[second] + A[third]
43+
if temp_sum > res:
44+
res = temp_sum
45+
# 因为是从后往前遍历,所以找到的第一个就是最大的
46+
break
47+
return res
48+
49+
def largestPerimeter2(self, A: List[int]) -> int:
50+
if len(A) < 3:
51+
return 0
52+
from itertools import combinations
53+
res = 0
54+
for each in combinations(A, 3):
55+
# 任意两边之和大于第三边
56+
if each[0] + each[1] <= each[2]:
57+
continue
58+
elif each[1] + each[2] <= each[0]:
59+
continue
60+
elif each[0] + each[2] <= each[1]:
61+
continue
62+
63+
# 任意两边之差小于第三边
64+
elif max(each[0], each[1]) - min(each[0], each[1]) >= each[2]:
65+
continue
66+
elif max(each[0], each[2]) - min(each[0], each[2]) >= each[1]:
67+
continue
68+
elif max(each[1], each[2]) - min(each[1], each[2]) >= each[0]:
69+
continue
70+
71+
elif sum(each) > res:
72+
res = sum(each)
73+
return res
74+
75+
76+
s = Solution()
77+
for _ in range(100):
78+
li = GenerateRandomList(20, 30)
79+
res_stand = s.largestPerimeter2(li)
80+
res = s.largestPerimeter(li[::])
81+
if res != res_stand:
82+
print(li)
83+
print("Done")

0 commit comments

Comments
 (0)