zoukankan      html  css  js  c++  java
  • 41. First Missing Positive

    description:

    Given an unsorted integer array, find the smallest missing positive integer.
    Note:
    Your algorithm should run in O(n) time and uses constant extra space.
    Example:

    Example 1:
    
    Input: [1,2,0]
    Output: 3
    
    Example 2:
    
    Input: [3,4,-1,1]
    Output: 2
    
    Example 3:
    
    Input: [7,8,9,11,12]
    Output: 1
    
    

    answer:

    class Solution {
    public:
        int firstMissingPositive(vector<int>& nums) {
            int n = nums.size();
            for(int i = 0; i < n; i++) {
                while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
                    swap (nums[i], nums[nums[i] - 1]); //先把数据放到正确的位置,就是说第一个位置放1,第二个位置放2
                }
            }
            
            for (int i = 0; i < n; i++) { // 然后进行遍历,那个位置不是应该的数就是答案
                if (nums[i] != i + 1) {
                    return i + 1;
                }
            }
            return n + 1;
        }
    };
    

    relative point get√:

    举个栗子:
    3,4,-1,1

    -1,4,3,1

    -1,1,3,4

    1,-1,3,4

    hint :

  • 相关阅读:
    SQL中的union
    SQL的类型转换
    Keytool生成证书
    Openssl生成证书
    Python示例-Json Parse
    Python示例-TCP Port Scan
    Python套接字
    TCP端口扫描
    Linux环境变量
    Python示例-Logging
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11168994.html
Copyright © 2011-2022 走看看