标签:nbsp leetcode limit exp mit 本质 custom mem 进制
题目:
给定一个函数f(x,y)和一个值z,返回所有正整数对x和y,满足f(x,y)== z。
f(x,y)为单调递增函数,即:
f(x,y)<f(x + 1,y)
f(x,y)<f(x,y + 1)
Example 1:
Input: function_id = 1, z = 5 Output: [[1,4],[2,3],[3,2],[4,1]] Explanation: function_id = 1 means that f(x, y) = x + y
限制条件:
1 <= function_id <= 9
1 <= z <= 100
保证f(x,y)== z的解在1 <= x,y <= 1000的范围内
如果1 <= x,y <= 1000,还可以保证f(x,y)可以容纳32位有符号整数
解法一:暴力破解,预计超时
def findSolution(self, customfunction, z): ans = [] for x in range(1,1001): for y in range(1,1001): if customfunction.f(x,y)==z: ans.append([x,y]) return ans
超时time limit exceeded
解法二:
#遍历,超时,本质上也是两个循环
class Solution: def findSolution(self, customfunction: ‘CustomFunction‘, z: int) -> List[List[int]]: res = [] for x in range(1, 1001):
y = 1001 while y > 1 and customfunction.f(x, y) > z: y -= 1 if customfunction.f(x, y) == z: res.append([x, y])
continue return res
解法三:linear time complexity
def findSolution(self, customfunction: ‘CustomFunction‘, z: int) -> List[List[int]]: x, y, ans = 1, 1000, [] while x < 1001 and y > 0: val = customfunction.f(x, y) if val > z: y -= 1 elif val < z: x += 1 else: ans += [[x, y]] x += 1 y -= 1 return ans
解法四:binary search
待debug????
def findSolution(self, customfunction: ‘CustomFunction‘, z: int) -> List[List[int]]: ans = [] for x in range(1, 1001): l, r ,ans = 1, 1001,[] while l < r: y = (l + r) // 2 if customfunction.f(x, y) < z: l = y + 1; else: r = y if customfunction.f(x, l) == z: ans += [[x, l]] return ans
optimized binary search
def findSolution(self, customfunction: ‘CustomFunction‘, z: int) -> List[List[int]]: left, right, ans, f = 1, 1001, [], customfunction.f for x in range(1, 1001): if f(x, left) > z or f(x, right) < z: continue l, r = left, right while l < r: y = (l + r) // 2 if f(x, y) < z: l = y + 1; else: r = y val = f(x, l) if val >= z: ans += [[x, l]] if val == z else [] right = l else: left = l return ans
左边界和右边界根据先前二进制搜索的结果而变化; 经过第一轮二分查找(成本计算)后,剩余的二分查找仅对x的每个值摊销O(1)(将其平均值表示为C)。因此,时间成本O(Cx +logy)时间:O(x + logy),空间:O(1),不包括返回列表。
标签:nbsp leetcode limit exp mit 本质 custom mem 进制
原文地址:https://www.cnblogs.com/jialinliu/p/13181950.html