1409. 查詢帶鍵的排列python
三種解法vim
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
# 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)
著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。app
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