Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the knumbers in the window. Each time the sliding window moves right by one position.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Therefore, return the max sliding window as [3,3,5,5,6,7].

Note: 
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?

这是一道非常有意思的题目。首先思路非常多,可以利用的数据结构也很多。

首先考虑暴力解法。即对每个sliding window都求最大值,复杂度为O(nk)。

下面考虑优化,对于求最大值,最小值,有一个非常好的数据结构,就是堆,这里需要在移动窗口的时候删除元素,如果用普通堆来做删除的复杂度为O(n)。显然不合适。这时候hashheap就可以派上用场,O(logk)时间求最大值,O(logk)时间删除元素。复杂度为O(nlogk)。空间复杂度为O(k)。代码如下:

class Solution:
    """
    @param nums: A list of integers.
    @return: The maximum number inside the window at each moving.
    """
    def maxSlidingWindow(self, nums, k):
        if not nums or len(nums) < k:
            return []
        res = []
        heap = HashHeap('max')
        for i in xrange(k):
            heap.add(nums[i])
        for i in xrange(k, len(nums)):
            res.append(heap.top())
            heap.delete(nums[i - k])
            heap.add(nums[i])
        res.append(heap.top())
        return res
       
class Node(object):
    """
    the type of class stored in the hashmap, in case there are many same heights
    in the heap, maintain the number
    """
    def __init__(self, id, num):
        self.id = id #id means its id in heap array
        self.num = num #number of same value in this id
        
class HashHeap(object):
    def __init__(self, mode):
        self.heap = []
        self.mode = mode
        self.size = 0
        self.hash = {}
    def top(self):
        return self.heap[0] if len(self.heap) > 0 else 0
        
    def contain(self, now):
        if self.hash.get(now):
            return True
        else:
            return False
        
    def isempty(self):
        return len(self.heap) == 0
        
    def _comparesmall(self, a, b): #compare function in different mode
        if a <= b:
            if self.mode == 'min':
                return True
            else:
                return False
        else:
            if self.mode == 'min':
                return False
            else:
                return True
    def _swap(self, idA, idB): #swap two values in heap, we also need to change
        valA = self.heap[idA]
        valB = self.heap[idB]
        
        numA = self.hash[valA].num
        numB = self.hash[valB].num
        self.hash[valB] = Node(idA, numB)
        self.hash[valA] = Node(idB, numA)
        self.heap[idA], self.heap[idB] = self.heap[idB], self.heap[idA]
    
    def add(self, now):  #the key, height in this place
        self.size += 1
        if self.hash.get(now):
            hashnow = self.hash[now]
            self.hash[now] = Node(hashnow.id, hashnow.num + 1)
        else:
            self.heap.append(now)
            self.hash[now] = Node(len(self.heap) - 1,1)
            self._siftup(len(self.heap) - 1)
            
    def pop(self):  #pop the top of heap
        self.size -= 1
        now = self.heap[0]
        hashnow = self.hash[now]
        num = hashnow.num
        if num == 1:
            self._swap(0, len(self.heap) - 1)
            self.hash.pop(now)
            self.heap.pop()
            self._siftdown(0)
        else:
            self.hash[now] = Node(0, num - 1)
        return now
        
    def delete(self, now):
        self.size -= 1
        hashnow = self.hash[now]
        id = hashnow.id
        num = hashnow.num
        if num == 1:
            self._swap(id, len(self.heap)-1) #like the common delete operation
            self.hash.pop(now)
            self.heap.pop()
            if len(self.heap) > id:
                self._siftup(id)
                self._siftdown(id)
        else:
            self.hash[now] = Node(id, num - 1)
            
    def parent(self, id):
      if id == 0:
        return -1

      return (id - 1) / 2

    def _siftup(self,id):
        while abs(id -1)/2 < id :  #iterative version
            parentId = (id - 1)/2 
            if self._comparesmall(self.heap[parentId],self.heap[id]):
                break
            else:
                self._swap(id, parentId)
            id = parentId
                
    def _siftdown(self, id): #iterative version
        while 2*id + 1 < len(self.heap):
            l = 2*id + 1
            r = l + 1
            small = id
            if self._comparesmall(self.heap[l], self.heap[id]):
                small = l
            if r < len(self.heap) and self._comparesmall(self.heap[r], self.heap[small]):
                small = r
            if small != id:
                self._swap(id, small)
            else:
                break
            id = small       

继续考虑是否可以优化,题目提示能否线性时间解决,其实这就比较tricky了,甚至提示使用deque,我也没有想出特别好的对策。其实这题应该想到对于这种求最大值的题目,单调队列是一个很好的选择,和单调栈类似,单调队列还有一个比较好的功能是:可以从头部删除元素,也就是对于过期的头部元素,可以比较及时的删除。那具体怎么做呢?

是单调递增队列还是单调递减队列?首先我们的元素增加都使从后段增加,队列尾部一般都是新增加的元素,我们无法保证它最大,那么选用单调递减队列,使其

头部是最大元素不失为一个很好的选择,之后我们继续思考,什么情况下进行增删,首先队首元素虽然是最大值,但是如果窗口移动后,它不在窗口内,则需要删除这个元素,每次窗口只移动一格,所以每次最多删除一个元素。另外我们每次增加新元素时,如果队列里有比它小的历史元素时,则这些元素本身不再有可能成为最大值,所以删除它们保持队列的单调递减性。单调栈和单调队列都有一个地方需要注意,就是相等时如何操作,如果队列里有元素和当前元素相等,我们是否需要删除,思考一下,其实应该删除,对于求最大值的情况,如果i已经进入窗口内,如果i对应的元素是这个窗口的最大值,前面那个和它相等的历史元素也就失效了。

注意和单调栈非常类似,单调队列存的同样是index。空间复杂度O(n),时间复杂度O(n),代码如下:

class Solution(object):
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        if not nums or len(nums) < k:
            return []
        #O(n), deque, you must can
        dq = collections.deque()
        res = []
        for i in xrange(len(nums)):
            if dq and dq[0] < i - k + 1: #the element out of range
                dq.popleft()
            while dq and nums[dq[-1]] <= nums[i]: #the element impossible to be the maximum value in deque
                dq.pop()
            dq.append(i)
            if i > k - 2:
                res.append(nums[dq[0]])
        return res

 

转载于:https://www.cnblogs.com/sherylwang/p/5655536.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个示例的自适应滑动窗算法航班排序的 Python 代码: ```python def adaptive_sliding_window_sort(flights, window_size=5, tolerance=2): """ Sorts a list of flights using an adaptive sliding window algorithm. :param flights: A list of Flight objects to be sorted :param window_size: The size of the sliding window (default is 5) :param tolerance: The tolerance level for the window (default is 2) :return: A sorted list of Flight objects """ sorted_flights = [flights[0]] # Start with the first flight already sorted for i in range(1, len(flights)): curr_flight = flights[i] # Find the best position for the current flight in the sorted list best_pos = find_best_position(sorted_flights, curr_flight, window_size, tolerance) # Insert the current flight into the sorted list at the best position sorted_flights.insert(best_pos, curr_flight) return sorted_flights def find_best_position(sorted_flights, curr_flight, window_size, tolerance): """ Finds the best position for the current flight in the sorted list using a sliding window algorithm. :param sorted_flights: A list of Flight objects already sorted :param curr_flight: The current Flight object to be inserted into the sorted list :param window_size: The size of the sliding window :param tolerance: The tolerance level for the window :return: The index of the best position for the current flight in the sorted list """ best_pos = len(sorted_flights) # Start with the end of the sorted list as the best position min_distance = float('inf') # Start with the maximum possible distance for i in range(len(sorted_flights) - window_size, len(sorted_flights)): # Calculate the distance between the current flight and each flight in the sliding window distance = calc_distance(curr_flight, sorted_flights[i]) # If the distance is within the tolerance level and smaller than the minimum distance so far, # update the minimum distance and the best position accordingly if distance <= tolerance and distance < min_distance: min_distance = distance best_pos = i return best_pos def calc_distance(flight1, flight2): """ Calculates the distance between two Flight objects based on their departure and arrival times. :param flight1: The first Flight object :param flight2: The second Flight object :return: The absolute difference between the departure time of flight1 and the arrival time of flight2 """ return abs(flight1.departure_time - flight2.arrival_time) class Flight: """ A simple Flight class with departure and arrival times. """ def __init__(self, departure_time, arrival_time): self.departure_time = departure_time self.arrival_time = arrival_time ``` 该算法的主要思路是,从前往后遍历航班列表,对于每个航班,找到在已排序的航班列表中最适合它的位置,并将其插入该位置。找到最适合位置的方法是使用滑动窗口算法,在已排序的航班列表中取最后 $n$ 个航班作为滑动窗口,并计算当前航班与滑动窗口中每个航班的时间差,如果时间差小于等于容忍度 $t$,则认为当前航班可以插入到这个位置。在滑动窗口中找到多个可插入位置时,选择时间差最小的位置作为最适合位置。 注意,该算法中的航班类 `Flight` 只包含了起飞时间和降落时间两个属性,实际应用中可能需要更多信息。另外,该算法只考虑了航班的起飞时间和降落时间,没有考虑到其他因素(如航班时长、中转时间等)可能对排序的影响。因此,该算法只是一个简单的示例,实际应用时需要根据具体情况进行调整和改进。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值