zoukankan      html  css  js  c++  java
  • 41. 缺失的第一个正数

    给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。

    请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。
     

    示例 1:

    输入:nums = [1,2,0]
    输出:3
    示例 2:

    输入:nums = [3,4,-1,1]
    输出:2
    示例 3:

    输入:nums = [7,8,9,11,12]
    输出:1
     

    提示:

    1 <= nums.length <= 5 * 105
    -231 <= nums[i] <= 231 - 1

    #include<iostream>
    #include<stack>
    #include<algorithm>
    #include<string>
    #include<vector>
    using namespace std;
    /*
    遍历一次数组查当前下标是否和值对应,如果不对应那这个下标就是答案,
    否则遍历完都没出现那么答案就是数组长度加1。
    */
    
    
    class Solution {
    public:
    	int firstMissingPositive(vector<int>& nums) {
    		sort(nums.begin(), nums.end());
    		int n = nums.size();
    		int res = 1;
    		for (int i = 0; i < n; ++i)
    		{
    			if (nums[i]>0)
    			{
    				if (nums[i] == res)
    				{
    					res++;
    				}
    				else if (nums[i]>res)
    				{
    					break;
    				}
    			}
    
    		}
    		return res;
    	}
    
    };
    
    int main()
    {
    	int a[1000];
    	int x;
    	int i = 0;
    	vector<int> vec;
    	int target;
    	while (cin >> a[i])
    	{
    		vec.push_back(a[i]);
    		i++;//注意这里i++对输出结果的影响
    		x = cin.get();
    		if (x == '
    ')
    			break;
    
    	}
    	int ans = Solution().firstMissingPositive(vec);
    	cout << ans << endl;
    	system("pause");
    	return 0;
    }
    

      

  • 相关阅读:
    em与rem之间的区别以及移动设备中的rem适配方案
    关于两个DIV之间的空白字符
    Bootstrap基本模板
    js 裁剪
    记一次诡异的bug
    Node切换版本
    git 撤销
    使用 iframe + postMessage 实现跨域通信
    <el-input>标签限制输入小数点
    vue elementyUI table :点击一行时选中这一行对应的复选框
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/14882817.html
Copyright © 2011-2022 走看看