【发布时间】:2021-08-28 03:44:19
【问题描述】:
我在 GeeksforGeeks 上尝试过提交时出现 TLE 错误的代码。
问题来了:
Geek 得到一个长度为 n 的 nums 数组和两个整数 x 和 y。极客有兴趣找到满足 x
帮助极客找出此类配对的总数。
示例 1:
Input: nums[] = {5,3,7,9,7,9,7,7},
x = 7, y = 19
Output: 1
Explanation: There is only one pair which
satisfies the given conditions. The pair is
(1,2).
示例 2:
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
提交后的输出:
运行时错误:
超出运行时错误时间限制
您的程序花费的时间比预期的要长。
预计时间限制 7.60 秒
提示:请优化您的代码并再次提交。
【问题讨论】:
-
跟随提示!
-
这就是本练习的重点——使用更高效的算法编写代码
-
尝试在 GeeksforGeeks 上搜索相同的问题。可能会有一篇文章解释如何优化它。
标签: python python-3.8