LeetCode 5381. Query the arrangement with key

5381. Query the arrangement with key

Idea: linked list

class Solution:
    def processQueries(self, queries: List[int], m: int) -> List[int]:
        res = []
        P = [i for i in range(1, m+1)]
        for i, q in enumerate(queries):
            index = P.index(q)
            # print(f'对于 i={i}: queries[i]={q}, P={P}', end=' ')
            tmp = P[index]
            for j in range(index)[::-1]:
                P[j+1] = P[j]
            P[0] = tmp
            res.append(index)
            # print(f'{q} 在 P 中的位置是 {index},接着我们把 {q} 移动到 P 的起始位置,得到 P={P} 。')
        return res

 

Published 248 original articles · Like 29 · Visits 30,000+

Guess you like

Origin blog.csdn.net/weixin_38603360/article/details/105466167