Find the nearest store – Python 3 (Week 13 – 02)

class Solution:
    """
    @param stores: The location of each store.
    @param houses: The location of each house.
    @return: The location of the nearest store to each house.
    """
    def findNearestStore(self, stores, houses):
        shmap = []
        ans = [-1] * len(houses)
        for i in range(len(stores)): #T O(n) S O(n)
            shmap.append([i, 's', stores[i]])
        for i in range(len(houses)):
            shmap.append([i, houses[i], houses[i]])
        
        shmap = sorted(shmap, key=lambda x: x[2]) #T nlogn spacen
        import math
        left = -math.inf
        for i in range(len(shmap)):
            if shmap[i][1] == 's':
                left = shmap[i][2]
            else:
                shmap[i][2] = left
                
                
        import math
        right = math.inf
        for i in range(len(shmap) - 1, -1, -1):
            
            if shmap[i][1] == 's':
                right = shmap[i][2]
            else:
                if (shmap[i][1] - shmap[i][2]) > (right - shmap[i][1]):
                    shmap[i][2] = right
                ans[shmap[i][0]] = shmap[i][2]
        
        return ans
            

Time O(n log n ). Space O(n). n is len(stores) + len(houses).

Leave a comment

Design a site like this with WordPress.com
Get started