[每日一题]124:第一个缺失正数

文章目录


题目描述

给出一个无序的数列,找出其中缺失的第一个正数,要求复杂度为 O(n) 如:[1,2,0],第一个缺失为3。 如:[3,4,-1,1],第一个缺失为2。

输入:
1,2,0

输出:
3

输入样例:
1,2,0
3,4,-1,1
-1,-3,-5
1,2,3
-1,-10,0

输出样例:
3
2
1
4
1

题解思路

  • 主要就是针对输入字符串格式的转换,剩下的就比较简单
  • 对数组排序,从前往后遍历,看是否有对应正数

代码实现:

#include <bits/stdc++.h>

using namespace std;

int main() {
    
    
    string s;

    while (cin >> s) {
    
    
        vector<int> v;

        while (s.size()) {
    
    
            int n = s.find(',');

            if (n == -1) {
    
    
                break;
            }
            string str = s.substr(0, n);
            int num = stoi(str);

            v.push_back(num);
            s = s.substr(n + 1);
        }
        int num = stoi(s);
        v.push_back(num);

        sort(v.begin(), v.end());
        
        int i = 0, res = 1;
        while (i < v.size()) {
    
    
            while (i < v.size() && v[i] == res) {
    
    
                ++i;
                ++res;
            }
            ++i;
        }
        cout << res << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/AngelDg/article/details/115249962
今日推荐