• 1409. 查询带键的排列


    1409. 查询带键的排列

    给你一个待查数组 queries ,数组中的元素为 1 到 m 之间的正整数。 请你根据以下规则处理所有待查项 queries[i](从 i=0 到 i=queries.length-1):

    一开始,排列 P=[1,2,3,...,m]。
    对于当前的 i ,请你找出待查项 queries[i] 在排列 P 中的位置(下标从 0 开始),然后将其从原位置移动到排列 P 的起始位置(即下标为 0 处)。注意, queries[i] 在 P 中的位置就是 queries[i] 的查询结果。
    
    • 1
    • 2

    请你以数组形式返回待查数组 queries 的查询结果。

    示例 1:

    输入:queries = [3,1,2,1], m = 5
    输出:[2,1,2,1]
    解释:待查数组 queries 处理如下:
    对于 i=0: queries[i]=3, P=[1,2,3,4,5], 3 在 P 中的位置是 2,接着我们把 3 移动到 P 的起始位置,得到 P=[3,1,2,4,5] 。
    对于 i=1: queries[i]=1, P=[3,1,2,4,5], 1 在 P 中的位置是 1,接着我们把 1 移动到 P 的起始位置,得到 P=[1,3,2,4,5] 。
    对于 i=2: queries[i]=2, P=[1,3,2,4,5], 2 在 P 中的位置是 2,接着我们把 2 移动到 P 的起始位置,得到 P=[2,1,3,4,5] 。
    对于 i=3: queries[i]=1, P=[2,1,3,4,5], 1 在 P 中的位置是 1,接着我们把 1 移动到 P 的起始位置,得到 P=[1,2,3,4,5] 。
    因此,返回的结果数组为 [2,1,2,1] 。

    示例 2:

    输入:queries = [4,1,2,2], m = 4
    输出:[3,1,2,0]

    示例 3:

    输入:queries = [7,5,5,8,3], m = 8
    输出:[6,5,0,7,5]

    这一题,力扣平台放水了,常规做法,就行,解题代码如下:

    /**
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* processQueries(int* queries, int queriesSize, int m, int* returnSize){
        int *re=(int *)malloc(sizeof(int )*queriesSize);
        int size=0;
        int arr[m];
        for(int i=0;i<m;i++){
            arr[i]=i+1;
    
        }
        for(int i=0;i<queriesSize;i++){
            int target=queries[i];
            int index=0;
            while(arr[index]!=target){
               index++;
            }
             re[size++]=index;
           
             while(index>0){
              arr[index]=arr[index-1];
              index--;
            }
            arr[index]=target;
           
    
    
        }
        *returnSize=size;
        return re;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
  • 相关阅读:
    聊聊SpringBoot单元测试
    Dijkstra求最短路(图解)
    ubuntu server 更改时区:上海
    一文带你拿下信号卷积—常见信号卷积
    Nginx搭建RTMP流媒体服务器(Ubuntu18.04)
    CentOS 升级 OpenSSL 至最新版教程
    HTMLDOM中的API之btoa和atob
    QTableView/QTableWidget设置单元格字体颜色及背景色
    ADB原理(第四篇:聊聊adb shell ps与adb shell ps有无双引号的区别)
    【VIM】初步认识VIM-2
  • 原文地址:https://blog.csdn.net/weixin_43327597/article/details/126880931