def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:
     n = len(nums1)
     chazhi = [abs(nums1[i] - nums2[i]) for i in range(n)]
     sum_chazhi = sum(chazhi)
     # print(chazhi)
     nums1_copy = sorted(nums1)
     # print(nums1_copy)
     ans = sum_chazhi
     for i in range(n):
         idx = bisect.bisect_left(nums1_copy, nums2[i])
         if idx == 0:
             ans = min(
                 ans,
                 sum_chazhi - chazhi[i] + abs(nums2[i] - nums1_copy[0]))
         elif idx == n:
             ans = min(
                 ans,
                 sum_chazhi - chazhi[i] + abs(nums2[i] - nums1_copy[-1]))
         else:
             ans = min(
                 ans,
                 sum_chazhi - chazhi[i] + abs(nums2[i] - nums1_copy[idx]),
                 sum_chazhi - chazhi[i] +
                 abs(nums2[i] - nums1_copy[idx - 1]))
     return ans % (10**9 + 7)
 def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
     """
     思路:
     1. 先计算二维前缀和presum
     2. 固定上下界,列坐标从左至右扫描,找到presum[j+1][r]-presum[i][l]<=k的最大值,即presum[i][l] >= presum[j+1][r]-k的最大值
     我们先将presum[j+1][r]-k有序插入arr中,每次遍历一个值后再arr中二分查找
     @param matrix:
     @param k:
     @return:
     """
     m, n = len(matrix), len(matrix[0])
     presum = [[0] * (n + 1) for _ in range(m + 1)]
     for i in range(m):
         for j in range(n):
             presum[i + 1][j + 1] = presum[i][j + 1] + presum[i + 1][j] + matrix[i][j] - presum[i][j]
     print(presum)
     res = float('-inf')
     # presum[i][r]-presum[i][l]<=k
     # 枚举上行
     for i in range(m):
         # 枚举下行
         for j in range(i, m):
             arr = [0]
             for r in range(n):
                 t = presum[j + 1][r + 1] - presum[i][r + 1]
                 index = bisect.bisect_left(arr, t - k)
                 if index < len(arr):
                     res = max(res, t - arr[index])
                 bisect.insort(arr, t)
     return res
Exemple #3
0
 def get(self, key):
     if key in self.h:
         val, freq, clock = self.h[key]
         self.key_arr.pop(bisect.bisect_left(self.key_arr, (freq, clock)))
         self.h[key] = (val, freq + 1, self.clock)
         bisect.insort_left(self.key_arr, (freq + 1, self.clock, key))
         self.clock += 1
         return val
     return -1
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums2.sort()  # 두번째 집합 정렬
        results = set()

        for n1 in nums1:
            index = bisect.bisect_left(nums2, n1)  # 이진 검색으로 일치 여부 판별
            if len(nums2) > 0 and index < len(nums2) and n1 == nums2[index]:
                results.add(n1)

        return results
 def ping(self, t):
     """
     :type t: int
     :rtype: int
     """
     from bisect import bisect
     self.nums.append(t)
     cur_pos = len(self.nums)
     prev_pos = bisect.bisect_left(self.nums, t - 3000)
     return cur_pos - prev_pos
Exemple #6
0
    def get(self, key: str, timestamp: int) -> str:
        k = bisect.bisect_left(list(self.storage[key].keys()), timestamp)

        print(k, self.storage[key])

        return self.storage[key][list(self.storage[key].keys())[k]]


# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)
Exemple #7
0
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        result = []
        tmp = sorted(nums[:k])

        result.append(tmp[-1])

        for i in range(1, len(nums) - k + 1):
            tmp.pop(bisect.bisect_left(tmp, nums[i - 1]))
            bisect.insort(tmp, nums[i + k - 1])

            result.append(tmp[-1])

        return result
Exemple #8
0
    def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
        ans = []
        length = len(nums)
        window = nums[:k]
        window.sort()
        ans.append(get_mid(window))

        for index in range(k, length):
            insert_value = nums[index]
            remove_value = nums[index - k]
            window.remove(remove_value)
            window.insert(bisect.bisect_left(window, insert_value),
                          insert_value)
            ans.append(get_mid(window))
        return ans
    def shortest(self, word1: str, word2: str) -> int:
        arr1 = self.dic[word1]
        arr2 = self.dic[word2]
        res = float('inf')
        for i in arr1:
            index = bisect.bisect_left(arr2, i)
            if index < len(arr2):
                res = min(res, abs(i - arr2[index]))
            if index > 0:
                res = min(res, abs(i - arr2[index - 1]))
            if index < len(arr2) - 1:
                res = min(res, abs(i - arr2[index + 1]))
        return res


# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(wordsDict)
# param_1 = obj.shortest(word1,word2)
Exemple #10
0
    def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:

        result = []

        def median(l):
            if len(l) % 2 == 1:
                return l[len(l) // 2]
            else:
                return (l[len(l) // 2 - 1] + l[len(l) // 2]) / 2

        tmp = sorted(nums[:k])

        result.append(median(tmp))

        for i in range(1, len(nums) - k + 1):
            tmp.pop(bisect.bisect_left(tmp, nums[i - 1]))
            bisect.insort(tmp, nums[i + k - 1])

            result.append(median(tmp))

        return result
Exemple #11
0
    def search(self, nums: List[int], target: int) -> int:
        #         # iterative
        #         left = 0
        #         right = len(nums) - 1

        #         while left <= right:
        #             mid = left + (right - left) // 2

        #             if target < nums[mid]:
        #                 right = mid - 1
        #             elif nums[mid] < target:
        #                 left = mid + 1
        #             else:
        #                 return mid

        #         return -1

        # 이진 검색 모듈
        index = bisect.bisect_left(nums, target)

        if index < len(nums) and nums[index] == target:
            return index
        return -1
Exemple #12
0
    def closestRoom(self, rooms: List[List[int]],
                    queries: List[List[int]]) -> List[int]:
        """
        思路:离线化,将查询数组和事物数组排序,降低时间复杂度(写了题解)
        @param rooms:
        @param queries:
        @return:
        """
        # from sortedcontainers import SortedSet
        m, n = len(rooms), len(queries)
        # 将rooms和queries按照size从大到小排序
        rooms.sort(key=lambda x: x[1], reverse=True)
        index = sorted(range(n), key=lambda i: queries[i][1], reverse=True)
        ids = []
        j = 0
        res = [-1] * n

        for i in index:
            preferred, minSize = queries[i]
            while j < m and rooms[j][1] >= minSize:
                bisect.insort(ids, rooms[j][0])
                j += 1
            if not ids:
                continue
            k = bisect.bisect_left(ids, preferred)
            if k == 0:
                res[i] = ids[0]
            elif k == len(ids):
                res[i] = ids[-1]
            else:
                if abs(ids[k] - preferred) < abs(ids[k - 1] - preferred):
                    res[i] = ids[k]
                else:
                    res[i] = ids[k - 1]

        return res
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
    i = bisect.bisect_left(breakpoints, score)
    print(breakpoints, score, i)
    return i
Exemple #14
0
def index(a, x):
    i = bisect.bisect_left(a, x)
    return i
Exemple #15
0
from bisect import bisect

if __name__ =='__main__':
    re = []
    for _ in range(int(input())):
        co = [int(i) for i in input().split(',')]
        re.append(co)
    p = sorted([[j, i] for i, (j, _) in enumerate(re)])
    # 【区间起点坐标,下标】组合并排序
    q = [bisect.bisect_left(p, [j, 0]) for _, j in re]
    # 用【终点坐标,0】查找可以往左插入的坐标,写成这样是为了对应数组P的形式
    print( [(p[i][1] if i < len(re) else -1) for i in q])
    # 如果下标没有越界就输出下标,否则输出-1
Exemple #16
0
 def get(self, index, snap_id):
     if snap_id in self.snapshot[index]:
         return self.snapshot[index][snap_id]
     else:
         key = bisect.bisect_left(list(self.snapshot[index].keys()))
         return self.snapshot[index][key]
Exemple #17
0
breakpoints = [30, 44, 66, 75, 85]


def grade(total):
    return grades[bisect(breakpoints, total)]


grade_map = map(grade, [33, 99, 77, 44, 12, 88])
grade_map
list(grade_map)

#%%
import bisect
import random
random.seed(3)
l = []
for i in range(10):
    r = random.randint(1, 50)
    pos = bisect.bisect_left(l, r)
    bisect.insort_left(l, r)
    print('%2d %2d' % (r, pos), l)
#%%
import bisect
import random
random.seed(3)
l = []
for i in range(10):
    r = random.randint(1, 50)
    pos = bisect.bisect(l, r)
    bisect.insort(l, r)
    print('%2d %2d' % (r, pos), l)