克服python代码的TLE(超出时间限制)错误
我在Geeksforgeks上试过代码,在提交时出现了错误 问题是:克服python代码的TLE(超出时间限制)错误,python,python-3.8,Python,Python 3.8,我在Geeksforgeks上试过代码,在提交时出现了错误 问题是: 给Geek一个长度为n的num数组和两个整数x和y。极客感兴趣的是找到对的总数(i,j),这样x通过使用组合,我们可以将O(n^2)减少到O(n)。试试这个: from itertools import combinations import math class Solution: def TotalPairs(self, nums, x, y): count = 0 _x = [a[
给Geek一个长度为n的num数组和两个整数x和y。极客感兴趣的是找到对的总数(i,j),这样x通过使用组合,我们可以将O(n^2)减少到O(n)。试试这个:
from itertools import combinations
import math
class Solution:
def TotalPairs(self, nums, x, y):
count = 0
_x = [a[0] * a[1] for a in list(combinations(nums, 2))]
for i in _x:
if x <= i <= y:
count += 1
return count
你得到了一个O(N^2)解
这里是我认为您可以做的,不必尝试泄露大部分代码,因为这毕竟是一个练习
基本上,对于数组中的每个数字num
,您需要找到数组中有多少个数字在
[ceil(x/num),floor(y/num)]
举个例子,如果x=7,y=19,则表示num=2。
那么满足条件的最小乘积是8,即
num*ceil(x/num)=2*ceil(7/2)=4
最大乘积同样为18,即
num*floor(y/num)=2*floor(19/2)=18
因此,对于2,列表中的数字必须在[4,9]范围内
这是否暗示了你应该做什么 首先对数组进行排序。
然后对于每个num:
1) 您可以使用二进制搜索查找ceil(x/num)和LOOR(y/num)的索引 2) 成对数为两个指数之差+1
这种方法的复杂性是,你需要O(NlogN)时间来排序,然后你运行所有需要O(N)时间的数字,对于每个数字,你执行两个二进制搜索操作,这就是
O(NlogN+2*NlogN)=O(NlogN)
按照提示!这就是本练习的全部要点——使用更高效的算法编写代码,尝试在Geeksforgek上搜索同一个问题。可能会有一篇文章解释如何优化它。不是真的。这里组合本身的复杂性是N选择2,所以它仍然是一个N^2的解决方案。嗯。。。没错,下面写下了NlogN解决方案的想法。
Input: nums[] = {3,5,5,2,6},
x = 8, y = 13
Output: 3
Explanation: Pairs which satisfiy the given
conditions are (2,4), (3,4), (4,5).
1<=n<=10^4
1<=nums[i]<=10^4
1<=x<=y<=10^8
class Solution:
def TotalPairs(self, nums, x, y):
count = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if x <= nums[i]*nums[j] <= y:
count += 1
return count
#{
# Driver Code Starts
if __name__ == '__main__':
T=int(input())
for i in range(T):
n, x, y = map(int, input().split())
nums = list(map(int, input().split()))
obj = Solution()
ans = obj.TotalPairs(nums, x, y)
print(ans)
# } Driver Code Ends
from itertools import combinations
import math
class Solution:
def TotalPairs(self, nums, x, y):
count = 0
_x = [a[0] * a[1] for a in list(combinations(nums, 2))]
for i in _x:
if x <= i <= y:
count += 1
return count
from itertools import combinations
import math
from functools import lru_cache
import functools
import time
class Solution:
def ignore_unhashable(func):
uncached = func.__wrapped__
attributes = functools.WRAPPER_ASSIGNMENTS + ('cache_info', 'cache_clear')
@functools.wraps(func, assigned=attributes)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except TypeError as error:
if 'unhashable type' in str(error):
return uncached(*args, **kwargs)
raise
wrapper.__uncached__ = uncached
return wrapper
@ignore_unhashable
@lru_cache(maxsize = 128)
def TotalPairs(self, nums, x, y):
count = 0
_x = [a[0] * a[1] for a in list(combinations(nums, 2))]
for i in _x:
if x <= i <= y:
count += 1
return count