import sys sys.setrecursionlimit(2000000) def CLOSESTADJPRICE(listk): closeprise =…
- User
import sys sys.setrecursionlimit(2000000)
def CLOSEST_ADJ_PRICE(listk): close_prise = abs(int(listk[1]) - int(listk[0])) for i in range(len(listk) - 2): i += 1 new_prise = abs(int(listk[i + 1]) - int(listk[i])) if new_prise < close_prise: close_prise = new_prise print(str(close_prise))
def CLOSEST_PRICE(listk): g = sorted(listk) close_prise = int(g[1]) - int(g[0]) for i in range(len(listk) - 2): i += 1 new_prise = int(g[i + 1]) - int(g[i]) if new_prise < close_prise: close_prise = new_prise print(str(close_prise))
m = input().split() a1 = int(m[0]) a2 = int(m[1]) n = input().split() k = [] for i in range(len(n)): k.append(int(n[i])) for i in range(a2): l = input().split() if l[0] == ‘BUY’: k.append(int(l[1])) elif l[0] == ‘CLOSEST_ADJ_PRICE’: CLOSEST_ADJ_PRICE(k) else: CLOSEST_PRICE(k)将该程序的时间复杂度优化为O(logn),可以使用二分查找算法来寻找最接近的价格。
- Assistant
import sys sys.setrecursionlimit(2000000)
def binary_search(arr, low, high, target): if low == high: return low
codemid = (low + high) // 2 if arr[mid] == target: return mid if arr[mid] < target: return binary_search(arr, mid+1, high, target) else: return binary_search(arr, low, mid, target)def closest_price(arr, target): low = 0 high = len(arr) - 1
codeidx = binary_search(arr, low, high, target) if idx == 0: return abs(arr[idx] - target) elif idx == len(arr) - 1: return abs(arr[idx] - target) else: return min(abs(arr[idx] - target), abs(arr[idx + 1] - target))m = input().split() a1 = int(m[0]) a2 = int(m[1]) n = input().split() k = [] for i in range(len(n)): k.append(int(n[i]))
for i in range(a2): l = input().split() if l[0] == 'BUY': k.append(int(l[1])) elif l[0] == 'CLOSEST_ADJ_PRICE': k = sorted(k) closest_adj_price = closest_price(k, int(l[1])) print(str(closest_adj_price)) else: closest = closest_price(k, int(l[1])) print(str(closest))
- User
该程序时间复杂度是?
- Assistant
该程序的时间复杂度是O(logn),其中n为价格列表的长度。这是因为在最坏情况下,二分查找算法需要将数组的范围缩小一半,直到找到目标元素或确定目标元素不存在。因此,时间复杂度是对数级别的。
- User
调整程序使它与原意一样
- Assistant
import sys sys.setrecursionlimit(2000000)
def closest_price(arr, target): low = 0 high = len(arr) - 1
codeif target < arr[low]: return arr[low] if target > arr[high]: return arr[high] while low <= high: mid = (low + high) // 2 if arr[mid] == target: return arr[mid] if arr[mid] > target: high = mid - 1 else: low = mid + 1 if abs(arr[low] - target) < abs(arr[high] - target): return arr[low] else: return arr[high]m = input().split() a1 = int(m[0]) a2 = int(m[1]) n = input().split() k = [] for i in range(len(n)): k.append(int(n[i]))
for i in range(a2): l = input().split() if l[0] == 'BUY': k.append(int(l[1])) elif l[0] == 'CLOSEST_ADJ_PRICE': closest_adj_price = closest_price(k, int(l[1])) print(str(closest_adj_price)) else: closest = closest_price(k, int(l[1])) print(str(closest))