1409. 查询带键的排列

三种解法

解法一 暴力

class Solution:
    def processQueries(self, queries: List[int], m: int) -> List[int]:
        m = min(m, max(queries))
        p = [i+1 for i in range(m)]
        ans = []
        for x in queries:
            i = p.index(x)
            ans.append(i)
            x = p.pop(i)
            p.insert(0, x)
        return ans

解法二 deque

# from collections import deque
class Solution:
    def processQueries(self, queries: List[int], m: int) -> List[int]:
        d = deque([i + 1 for i in range(min(m, max(queries)))])
        ans = []
        for q in queries:
            i = d.index(q)
            ans.append(i)
            d.remove(q)
            d.appendleft(q)
        return ans

解法三 树状数组

转载自:

作者:etworker
链接:https://leetcode-cn.com/probl...
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

class Fenwick:
    def __init__(self, n):
        sz = 1
        while sz <= n:
            sz *= 2
        self.size = sz
        self.data = [0] * sz

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i < self.size:
            self.data[i] += x
            i += i & -i

class Solution:
    def processQueries(self, queries: List[int], m: int) -> List[int]:
        # - because queries.length <= m, so use double space 
        fenw = Fenwick(2 * m)

        # - vimap keeps the position of value i
        vimap = {}
        for i in range(1, m + 1):
            fenw.add(i + m, 1)
            vimap[i] = i + m

        # - next head position
        cur = m
        
        ans = []
        for q in queries:
            # - get current position of value q
            i = vimap.pop(q)

            # - rank means index
            rank = fenw.sum(i-1)
            ans.append(rank)
            
            # - move q to the head position
            vimap[q] = cur

            # - all elements behind position i will move left, so rank--
            fenw.add(i, -1)

            # - all elements value shift +1
            fenw.add(cur, 1)

            # - move next head position to left
            cur -= 1
            
        return ans

sxwxs
292 声望20 粉丝

计算机专业学生