博客
关于我
1539. Kth Missing Positive Number
阅读量:279 次
发布时间:2019-03-01

本文共 991 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要找到缺失在给定数组中的第k个正整数。数组中的数是严格递增的正整数,但可能存在缺失的数,我们需要找到这些缺失数中的第k个。

方法思路

我们可以使用两个变量来跟踪当前位置和缺失的数量。具体步骤如下:

  • 初始化两个变量countcur,分别用于记录缺失的数量和当前位置。
  • 遍历数组中的每个元素,逐步检查是否存在缺失的数。
  • 当发现缺失的数时,继续检查直到找到第k个缺失的数。
  • 处理完数组后,继续检查后续可能的缺失数,直到找到第k个。
  • 这种方法确保了我们能够高效地找到第k个缺失的数,避免了不必要的重复计算。

    解决代码

    #include 
    using namespace std;
    int findKthPositive(vector
    & arr, int k) {
    int count = 0;
    int cur = 0;
    for (int num : arr) {
    cur++;
    while (cur < num) {
    count++;
    if (count == k) {
    return cur;
    }
    cur++;
    }
    }
    while (count < k) {
    cur++;
    count++;
    if (count == k) {
    return cur;
    }
    }
    return -1; // This line is theoretically unreachable as per problem constraints
    }

    代码解释

  • 初始化变量count用于记录缺失的数量,cur用于跟踪当前位置。
  • 遍历数组:对于数组中的每个元素,先增加cur,然后检查是否存在缺失的数。如果发现缺失的数,继续检查直到找到第k个缺失的数。
  • 处理后续缺失数:处理完数组后,继续检查后续可能的缺失数,直到找到第k个。
  • 这种方法确保了我们能够高效地找到第k个缺失的数,避免了不必要的重复计算。

    转载地址:http://saqo.baihongyu.com/

    你可能感兴趣的文章
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>