1534. 统计好三元组
1.我的思路:枚举
利用嵌套循环解决问题,但是这个效率低,水平低。没有含金量
主要语法:
abs( x ):函数返回 x(数字)的绝对值,如果参数是一个复数,则返回它的大小。
list.append(obj):
class Solution(object): def countGoodTriplets(self, arr, a, b, c): """ :type arr: List[int] :type a: int :type b: int :type c: int :rtype: int """ list=[] for i in range(0,len(arr)-2): for j in range(i+1,len(arr)-1): for k in range(j+1,len(arr)): if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c: list.append([arr[i],arr[j],arr[k]]) return len(list)2.根据官方也容易想到的思路:双重循环优化
先进行两重循环的判断,在进行综合验证
class Solution(object): def countGoodTriplets(self, arr, a, b, c): """ :type arr: List[int] :type a: int :type b: int :type c: int :rtype: int """ list=[] for i in range(0,len(arr)-2): for j in range(i+1,len(arr)-1): if abs(arr[i] - arr[j]) >= a: continue for k in range(j+1,len(arr)): if abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c: list.append([arr[i],arr[j],arr[k]]) return len(list)