📌  相关文章
📜  查找未排序数组中缺失的最小正数 |设置 1

📅  最后修改于: 2022-05-13 01:57:52.887000             🧑  作者: Mango

查找未排序数组中缺失的最小正数 |设置 1

您将获得一个包含正元素和负元素的未排序数组。您必须使用恒定的额外空间在 O(n) 时间内从数组中找到最小的正数。您可以修改原始数组。

例子

Input:  {2, 3, 7, 6, 8, -1, -10, 15}
 Output: 1

 Input:  { 2, 3, -7, 6, 8, 1, -10, 15 }
 Output: 4

 Input: {1, 1, 0, -1, -2}
 Output: 2

解决此问题的一种简单方法是搜索所有正整数,从给定数组中的 1 开始。我们可能必须在给定数组中搜索最多 n+1 个数字。所以这个解决方案在最坏的情况下需要 O(n^2) 。

我们可以使用排序以较低的时间复杂度来解决它。我们可以在 O(nLogn) 时间内对数组进行排序。一旦数组被排序,那么我们需要做的就是对数组进行线性扫描。所以这种方法需要 O(nLogn + n) 时间,即 O(nLogn)。

我们也可以使用散列。我们可以为给定数组中的所有正元素构建一个哈希表。一旦构建了哈希表。我们可以在哈希表中查找从 1 开始的所有正整数。一旦我们找到哈希表中不存在的数字,我们就会返回它。这种方法平均可能需要 O(n) 时间,但它需要 O(n) 额外空间。

AO(n) 时间和 O(1) 额外空间解决方案:
这个想法与这篇文章相似。我们使用数组元素作为索引。为了标记元素 x 的存在,我们将索引 x 处的值更改为负数。但是,如果存在非正数(-ve 和 0),则此方法不起作用。因此,我们首先将正数与负数分开,然后应用该方法。

以下是两步算法。
1)将正数与其他数分开,即将所有非正数移到左侧。在下面的代码中, segregate()函数完成了这部分工作。
2)现在我们可以忽略非正元素,只考虑数组中包含所有正元素的部分。我们遍历包含所有正数的数组并标记元素 x 的存在,我们将索引 x 处的值的符号更改为负数。我们再次遍历数组并打印第一个具有正值的索引。在下面的代码中,findMissingPositive()函数完成了这部分工作。请注意,在 findMissingPositive 中,我们从值中减去 1,因为 C 中的索引从 0 开始。

C++
/* C++ program to find the
   smallest positive missing number */
#include 
using namespace std;
 
/* Utility to swap to integers */
void swap(int* a, int* b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
 
/* Utility function that puts all
non-positive (0 and negative) numbers on left
side of arr[] and return count of such numbers */
int segregate(int arr[], int size)
{
    int j = 0, i;
    for (i = 0; i < size; i++) {
        if (arr[i] <= 0) {
            swap(&arr[i], &arr[j]);
           
            // increment count of
            // non-positive integers
            j++;
        }
    }
 
    return j;
}
 
/* Find the smallest positive missing number
in an array that contains all positive integers */
int findMissingPositive(int arr[], int size)
{
    int i;
 
    // Mark arr[i] as visited by
    // making arr[arr[i] - 1] negative.
    // Note that 1 is subtracted
    // because index start
    // from 0 and positive numbers start from 1
    for (i = 0; i < size; i++) {
        if (abs(arr[i]) - 1 < size && arr[abs(arr[i]) - 1] > 0)
            arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];
    }
 
    // Return the first index
    // value at which is positive
    for (i = 0; i < size; i++)
        if (arr[i] > 0)
           
            // 1 is added because
            // indexes start from 0
            return i + 1;
 
    return size + 1;
}
 
/* Find the smallest positive missing
number in an array that contains
both positive and negative integers */
int findMissing(int arr[], int size)
{
     
    // First separate positive
    // and negative numbers
    int shift = segregate(arr, size);
 
    // Shift the array and call
    // findMissingPositive for
    // positive part
    return findMissingPositive(arr + shift,
                               size - shift);
}
 
// Driver code
int main()
{
    int arr[] = { 0, 10, 2, -10, -20 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    int missing = findMissing(arr, arr_size);
    cout << "The smallest positive missing number is " << missing;
    return 0;
}
 
// This is code is contributed by rathbhupendra


C
/* C program to find the smallest
   positive missing number */
#include 
#include 
 
/* Utility to swap to integers */
void swap(int* a, int* b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
 
/* Utility function that puts all
non-positive (0 and negative) numbers on left
side of arr[] and return count of such numbers */
int segregate(int arr[], int size)
{
    int j = 0, i;
    for (i = 0; i < size; i++) {
        if (arr[i] <= 0) {
            swap(&arr[i], &arr[j]);
            j++; // increment count of non-positive integers
        }
    }
 
    return j;
}
 
/* Find the smallest positive missing number
in an array that contains all positive integers */
int findMissingPositive(int arr[], int size)
{
    int i;
 
    // Mark arr[i] as visited by
    // making arr[arr[i] - 1] negative.
    // Note that 1 is subtracted
    // because index start
    // from 0 and positive numbers start from 1
    for (i = 0; i < size; i++) {
        if (abs(arr[i]) - 1 < size && arr[abs(arr[i]) - 1] > 0)
            arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];
    }
 
    // Return the first index value at which is positive
    for (i = 0; i < size; i++)
        if (arr[i] > 0)
            // 1 is added because indexes start from 0
            return i + 1;
 
    return size + 1;
}
 
/* Find the smallest positive missing
number in an array that contains
both positive and negative integers */
int findMissing(int arr[], int size)
{
    // First separate positive and negative numbers
    int shift = segregate(arr, size);
 
    // Shift the array and call findMissingPositive for
    // positive part
    return findMissingPositive(arr + shift, size - shift);
}
 
// Driver code
int main()
{
    int arr[] = { 0, 10, 2, -10, -20 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    int missing = findMissing(arr, arr_size);
    printf("The smallest positive missing number is %d ", missing);
    getchar();
    return 0;
}


Java
// Java program to find the smallest
// positive missing number
import java.util.*;
 
class Main {
 
    /* Utility function that puts all non-positive
       (0 and negative) numbers on left side of
       arr[] and return count of such numbers */
    static int segregate(int arr[], int size)
    {
        int j = 0, i;
        for (i = 0; i < size; i++) {
            if (arr[i] <= 0) {
                int temp;
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                // increment count of non-positive
                // integers
                j++;
            }
        }
 
        return j;
    }
 
    /* Find the smallest positive missing
       number in an array that contains
       all positive integers */
    static int findMissingPositive(int arr[], int size)
    {
        int i;
 
        // Mark arr[i] as visited by making
        // arr[arr[i] - 1] negative. Note that
        // 1 is subtracted because index start
        // from 0 and positive numbers start from 1
        for (i = 0; i < size; i++) {
            int x = Math.abs(arr[i]);
            if (x - 1 < size && arr[x - 1] > 0)
                arr[x - 1] = -arr[x - 1];
        }
 
        // Return the first index value at which
        // is positive
        for (i = 0; i < size; i++)
            if (arr[i] > 0)
                return i + 1; // 1 is added because indexes
        // start from 0
 
        return size + 1;
    }
 
    /* Find the smallest positive missing
       number in an array that contains
       both positive and negative integers */
    static int findMissing(int arr[], int size)
    {
        // First separate positive and
        // negative numbers
        int shift = segregate(arr, size);
        int arr2[] = new int[size - shift];
        int j = 0;
        for (int i = shift; i < size; i++) {
            arr2[j] = arr[i];
            j++;
        }
        // Shift the array and call
        // findMissingPositive for
        // positive part
        return findMissingPositive(arr2, j);
    }
     
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 0, 10, 2, -10, -20 };
        int arr_size = arr.length;
        int missing = findMissing(arr, arr_size);
        System.out.println("The smallest positive missing number is " + missing);
    }
}


Python3
''' Python3 program to find the
smallest positive missing number '''
 
''' Utility function that puts all
non-positive (0 and negative) numbers on left
side of arr[] and return count of such numbers '''
def segregate(arr, size):
    j = 0
    for i in range(size):
        if (arr[i] <= 0):
            arr[i], arr[j] = arr[j], arr[i]
            j += 1 # increment count of non-positive integers
    return j
 
 
''' Find the smallest positive missing number
in an array that contains all positive integers '''
def findMissingPositive(arr, size):
     
    # Mark arr[i] as visited by
    # making arr[arr[i] - 1] negative.
    # Note that 1 is subtracted
    # because index start
    # from 0 and positive numbers start from 1
    for i in range(size):
        if (abs(arr[i]) - 1 < size and arr[abs(arr[i]) - 1] > 0):
            arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]
             
    # Return the first index value at which is positive
    for i in range(size):
        if (arr[i] > 0):
             
            # 1 is added because indexes start from 0
            return i + 1
    return size + 1
 
''' Find the smallest positive missing
number in an array that contains
both positive and negative integers '''
def findMissing(arr, size):
     
    # First separate positive and negative numbers
    shift = segregate(arr, size)
     
    # Shift the array and call findMissingPositive for
    # positive part
    return findMissingPositive(arr[shift:], size - shift)
     
# Driver code
arr = [ 0, 10, 2, -10, -20 ]
arr_size = len(arr)
missing = findMissing(arr, arr_size)
print("The smallest positive missing number is ", missing)
 
# This code is contributed by Shubhamsingh10


C#
// C# program to find the smallest
// positive missing number
using System;
 
class main {
 
    // Utility function that puts all
    // non-positive (0 and negative)
    // numbers on left side of arr[]
    // and return count of such numbers
    static int segregate(int[] arr, int size)
    {
        int j = 0, i;
        for (i = 0; i < size; i++) {
            if (arr[i] <= 0) {
                int temp;
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
 
                // increment count of non-positive
                // integers
                j++;
            }
        }
 
        return j;
    }
 
    // Find the smallest positive missing
    // number in an array that contains
    // all positive integers
    static int findMissingPositive(int[] arr, int size)
    {
        int i;
 
        // Mark arr[i] as visited by making
        // arr[arr[i] - 1] negative. Note that
        // 1 is subtracted as index start from
        // 0 and positive numbers start from 1
        for (i = 0; i < size; i++) {
            if (Math.Abs(arr[i]) - 1 < size && arr[ Math.Abs(arr[i]) - 1] > 0)
                arr[ Math.Abs(arr[i]) - 1] = -arr[ Math.Abs(arr[i]) - 1];
        }
 
        // Return the first index value at
        // which is positive
        for (i = 0; i < size; i++)
            if (arr[i] > 0)
                return i + 1;
 
        // 1 is added because indexes
        // start from 0
        return size + 1;
    }
 
    // Find the smallest positive
    // missing number in array that
    // contains both positive and
    // negative integers
    static int findMissing(int[] arr, int size)
    {
 
        // First separate positive and
        // negative numbers
        int shift = segregate(arr, size);
        int[] arr2 = new int[size - shift];
        int j = 0;
 
        for (int i = shift; i < size; i++) {
            arr2[j] = arr[i];
            j++;
        }
 
        // Shift the array and call
        // findMissingPositive for
        // positive part
        return findMissingPositive(arr2, j);
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 0, 10, 2, -10, -20 };
        int arr_size = arr.Length;
        int missing = findMissing(arr, arr_size);
        Console.WriteLine("The smallest positive missing number is " + missing);
    }
}
 
// This code is contributed by Anant Agarwal.


Javascript


C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the first missing positive
// number from the given unsorted array
int firstMissingPos(int A[], int n)
{
 
    // To mark the occurrence of elements
    bool present[n + 1] = { false };
 
    // Mark the occurrences
    for (int i = 0; i < n; i++) {
 
        // Only mark the required elements
        // All non-positive elements and
        // the elements greater n + 1 will never
        // be the answer
        // For example, the array will be {1, 2, 3}
        // in the worst case and the result
        // will be 4 which is n + 1
        if (A[i] > 0 && A[i] <= n)
            present[A[i]] = true;
    }
 
    // Find the first element which didn't
    // appear in the original array
    for (int i = 1; i <= n; i++)
        if (!present[i])
            return i;
 
    // If the original array was of the
    // type {1, 2, 3} in its sorted form
    return n + 1;
}
 
// Driver code
int main()
{
 
    int A[] = { 0, 10, 2, -10, -20 };
    int size = sizeof(A) / sizeof(A[0]);
    cout << firstMissingPos(A, size);
}
 
// This code is contributed by gp6


Java
// Java Program to find the smallest
// positive missing number
import java.util.*;
public class GFG {
 
    static int solution(int[] A)
    {
        int n = A.length;
      //Let this 1e6 be the maximum elemnt provided in the array;
          int N=1000010;
 
        // To mark the occurrence of elements
        boolean[] present = new boolean[N];
           
          int maxele=Integer.MIN_VALUE;
 
        // Mark the occurrences
        for (int i = 0; i < n; i++) {
 
            // Only mark the required elements
            // All non-positive elements and
            // the elements greater n + 1 will never
            // be the answer
            // For example, the array will be {1, 2, 3}
            // in the worst case and the result
            // will be 4 which is n + 1
            if (A[i] > 0 && A[i] <= n)
                present[A[i]] = true;
           
          //find the maximum element so that if all the elements are in order can directly return the next number
          maxele=Math.max(maxele,A[i]);
        }
 
        // Find the first element which didn't
        // appear in the original array
        for (int i = 1; i < N; i++)
            if (!present[i])
                return i;
 
        // If the original array was of the
        // type {1, 2, 3} in its sorted form
        return maxele + 1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int A[] = { 0, 10, 2, -10, -20 };
        System.out.println(solution(A));
      int arr[]={-2,-1,0,1,2,3,4};
      System.out.println(solution(arr));
    }
}
// This code is contributed by Arava Sai Teja


Python3
# Python3 Program to find the smallest
# positive missing number
 
 
def solution(A):  # Our original array
 
    m = max(A)  # Storing maximum value
    if m < 1:
 
        # In case all values in our array are negative
        return 1
    if len(A) == 1:
 
        # If it contains only one element
        return 2 if A[0] == 1 else 1
    l = [0] * m
    for i in range(len(A)):
        if A[i] > 0:
            if l[A[i] - 1] != 1:
 
                # Changing the value status at the index of our list
                l[A[i] - 1] = 1
    for i in range(len(l)):
 
        # Encountering first 0, i.e, the element with least value
        if l[i] == 0:
            return i + 1
            # In case all values are filled between 1 and m
    return i + 2
 
# Driver Code
A = [0, 10, 2, -10, -20]
print(solution(A))


C#
// C# Program to find the smallest
// positive missing number
using System;
using System.Linq;
 
class GFG {
    static int solution(int[] A)
    {
        // Our original array
 
        int m = A.Max(); // Storing maximum value
 
        // In case all values in our array are negative
        if (m < 1) {
            return 1;
        }
        if (A.Length == 1) {
 
            // If it contains only one element
            if (A[0] == 1) {
                return 2;
            }
            else {
                return 1;
            }
        }
        int i = 0;
        int[] l = new int[m];
        for (i = 0; i < A.Length; i++) {
            if (A[i] > 0) {
                // Changing the value status at the index of
                // our list
                if (l[A[i] - 1] != 1) {
                    l[A[i] - 1] = 1;
                }
            }
        }
 
        // Encountering first 0, i.e, the element with least
        // value
        for (i = 0; i < l.Length; i++) {
            if (l[i] == 0) {
                return i + 1;
            }
        }
 
        // In case all values are filled between 1 and m
        return i + 2;
    }
 
    // Driver code
    public static void Main()
    {
        int[] A = { 0, 10, 2, -10, -20 };
        Console.WriteLine(solution(A));
    }
}
 
// This code is contributed by PrinciRaj1992


PHP
 0)
        {
            if ($l[$A[$i] - 1] != 1)
            {
                 
                //Changing the value status at the index of our list
                $l[$A[$i] - 1] = 1;
            }
        }
    }
    for ($i = 0;$i < sizeof($l); $i++)
    {
          
        //Encountering first 0, i.e, the element with least value
        if ($l[$i] == 0)
            return $i+1;
    }
            //In case all values are filled between 1 and m
    return $i+2;   
}
 
// Driver Code
$A = array(0, 10, 2, -10, -20);
echo solution($A);
return 0;
?>


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function for finding the first missing positive number
 
int firstMissingPositive(int arr[], int n)
{
    int ptr = 0;
 
    // Check if 1 is present in array or not
    for (int i = 0; i < n; i++) {
        if (arr[i] == 1) {
            ptr = 1;
            break;
        }
    }
 
    // If 1 is not present
    if (ptr == 0)
        return 1;
 
    // Changing values to 1
    for (int i = 0; i < n; i++)
        if (arr[i] <= 0 || arr[i] > n)
            arr[i] = 1;
 
    // Updating indices according to values
    for (int i = 0; i < n; i++)
        arr[(arr[i] - 1) % n] += n;
 
    // Finding which index has value less than n
    for (int i = 0; i < n; i++)
        if (arr[i] <= n)
            return i + 1;
 
    // If array has values from 1 to n
    return n + 1;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    int ans = firstMissingPositive(arr, n);
 
    cout << ans;
 
    return 0;
}


C
// C program for the above approach
#include 
#include 
 
// Function for finding the first
// missing positive number
int firstMissingPositive(int arr[], int n)
{
    int ptr = 0;
 
    // Check if 1 is present in array or not
    for(int i = 0; i < n; i++)
    {
        if (arr[i] == 1)
        {
            ptr = 1;
            break;
        }
    }
 
    // If 1 is not present
    if (ptr == 0)
        return 1;
 
    // Changing values to 1
    for(int i = 0; i < n; i++)
        if (arr[i] <= 0 || arr[i] > n)
            arr[i] = 1;
 
    // Updating indices according to values
    for(int i = 0; i < n; i++)
        arr[(arr[i] - 1) % n] += n;
 
    // Finding which index has value less than n
    for(int i = 0; i < n; i++)
        if (arr[i] <= n)
            return i + 1;
 
    // If array has values from 1 to n
    return n + 1;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int ans = firstMissingPositive(arr, n);
     
    printf("%d", ans);
     
    return 0;
}
 
// This code is contributed by shailjapriya


Java
// Java program for the above approach
import java.util.Arrays;
 
class GFG{
 
// Function for finding the first
// missing positive number
static int firstMissingPositive(int arr[], int n)
{
    int ptr = 0;
 
    // Check if 1 is present in array or not
    for(int i = 0; i < n; i++)
    {
        if (arr[i] == 1)
        {
            ptr = 1;
            break;
        }
    }
 
    // If 1 is not present
    if (ptr == 0)
        return (1);
 
    // Changing values to 1
    for(int i = 0; i < n; i++)
        if (arr[i] <= 0 || arr[i] > n)
            arr[i] = 1;
 
    // Updating indices according to values
    for(int i = 0; i < n; i++)
        arr[(arr[i] - 1) % n] += n;
 
    // Finding which index has value less than n
    for(int i = 0; i < n; i++)
        if (arr[i] <= n)
            return (i + 1);
 
    // If array has values from 1 to n
    return (n + 1);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
    int n = arr.length;
    int ans = firstMissingPositive(arr, n);
     
    System.out.println(ans);
}
}
 
// This code is contributed by shailjapriya


Python3
# Python3 program for the above approach
 
# Function for finding the first missing
# positive number
def firstMissingPositive(arr, n):
     
    ptr = 0
     
    # Check if 1 is present in array or not
    for i in range(n):
        if arr[i] == 1:
            ptr = 1
            break
         
    # If 1 is not present
    if ptr == 0:
        return(1)
         
    # Changing values to 1
    for i in range(n):
        if arr[i] <= 0 or arr[i] > n:
            arr[i] = 1
             
    # Updating indices according to values
    for i in range(n):
        arr[(arr[i] - 1) % n] += n
         
    # Finding which index has value less than n
    for i in range(n):
        if arr[i] <= n:
            return(i + 1)
 
    # If array has values from 1 to n
    return(n + 1)
 
# Driver Code
 
# Given array
A = [ 2, 3, -7, 6, 8, 1, -10, 15 ]
 
# Size of the array
N = len(A)
 
# Function call
print(firstMissingPositive(A, N))
 
# This code is contributed by shailjapriya


C#
// C# program for the above approach
using System;
using System.Linq;
   
class GFG{
 
// Function for finding the first missing
// positive number    
static int firstMissingPositive(int[] arr, int n)
{
    int ptr = 0;
     
    // Check if 1 is present in array or not
    for(int i = 0; i < n; i++)
    {
        if (arr[i] == 1)
        {
            ptr = 1;
            break;
        }
    }
   
    // If 1 is not present
    if (ptr == 0)
        return 1;
   
    // Changing values to 1
    for(int i = 0; i < n; i++)
        if (arr[i] <= 0 || arr[i] > n)
            arr[i] = 1;
   
    // Updating indices according to values
    for(int i = 0; i < n; i++)
        arr[(arr[i] - 1) % n] += n;
   
    // Finding which index has value less than n
    for(int i = 0; i < n; i++)
        if (arr[i] <= n)
            return i + 1;
   
    // If array has values from 1 to n
    return n + 1;
}
 
// Driver code
public static void Main()
{
    int[] A = { 2, 3, -7, 6, 8, 1, -10, 15 };
    int n = A.Length;
    int ans = firstMissingPositive(A, n);
     
    Console.WriteLine(ans);
}
}
 
// This code is contributed by shailjapriya


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function for finding the first
// missing positive number
int firstMissingPositive(int arr[], int n)
{
     
    // Loop to traverse the whole array
    for (int i = 0; i < n; i++) {
       
        // Loop to check boundary
        // condition and for swapping
        while (arr[i] >= 1 && arr[i] <= n
               && arr[i] != arr[arr[i] - 1]) {
            swap(arr[i], arr[arr[i] - 1]);
        }
    }
   
    // Checking any element which
    // is not equal to i+1
    for (int i = 0; i < n; i++) {
        if (arr[i] != i + 1) {
            return i + 1;
        }
    }
   
    // Nothing is present return last index
    return n + 1;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    int ans = firstMissingPositive(arr, n);
 
    cout << ans;
 
    return 0;
}
// This code is contributed by Harsh kedia


Java
// Java program for the above approach
import java.util.Arrays;
 
class GFG{
 
// Function for finding the first
// missing positive number
static int firstMissingPositive(int arr[], int n)
{
 
    // Check if 1 is present in array or not
    for(int i = 0; i < n; i++)
    {
       
      // Loop to check boundary
      // condition and for swapping
      while (arr[i] >= 1 && arr[i] <= n
             && arr[i] != arr[arr[i] - 1]) {
         
        int temp=arr[arr[i]-1];
            arr[arr[i]-1]=arr[i];
            arr[i]=temp;
      }
    }
 
    // Finding which index has value less than n
    for(int i = 0; i < n; i++)
        if (arr[i] != i + 1)
            return (i + 1);
 
    // If array has values from 1 to n
    return (n + 1);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = {2, 3, -7, 6, 8, 1, -10, 15 };
    int n = arr.length;
    int ans = firstMissingPositive(arr, n);
     
    System.out.println(ans);
}
}
 
// This code is contributed by mohit kumar 29.


Python3
# Python program for the above approach
# Function for finding the first
# missing positive number
def firstMissingPositive(arr, n):
 
    # Loop to traverse the whole array
    for i in range(n):
       
        # Loop to check boundary
        # condition and for swapping
        while (arr[i] >= 1 and arr[i] <= n
               and arr[i] != arr[arr[i] - 1]):
            temp = arr[i]
            arr[i] = arr[arr[i] - 1]
            arr[temp - 1] = temp
     
    # Checking any element which
    # is not equal to i+1
    for i in range(n):
        if (arr[i] != i + 1):
            return i + 1
         
    # Nothing is present return last index
    return n + 1
 
# Driver code
arr = [ 2, 3, -7, 6, 8, 1, -10, 15 ];
n = len(arr)
ans = firstMissingPositive(arr, n)
print(ans)
 
# This code is contributed by shivanisinghss2110


C#
// C# program for the above approach
using System;
public class GFG{
 
  // Function for finding the first
  // missing positive number
  static int firstMissingPositive(int[] arr, int n)
  {
 
    // Check if 1 is present in array or not
    for(int i = 0; i < n; i++)
    {
 
      // Loop to check boundary
      // condition and for swapping
      while (arr[i] >= 1 && arr[i] <= n
             && arr[i] != arr[arr[i] - 1]) {
 
        int temp = arr[arr[i] - 1];
        arr[arr[i] - 1] = arr[i];
        arr[i] = temp;
      }
    }
 
    // Finding which index has value less than n
    for(int i = 0; i < n; i++)
      if (arr[i] != i + 1)
        return (i + 1);
 
    // If array has values from 1 to n
    return (n + 1);
  }
 
  // Driver Code
 
  static public void Main ()
  {
 
    int[] arr = {2, 3, -7, 6, 8, 1, -10, 15 };
    int n = arr.Length;
    int ans = firstMissingPositive(arr, n);
 
    Console.WriteLine(ans);
  }
}
 
// This code is contributed by ab2127


Javascript


C++
#include 
using namespace std;
int firstMissingPositive(vector& nums) {
sort(nums.begin(),nums.end());
int ans=1;
for(int i=0;iarr={-1,0,8,1};
cout << firstMissingPositive(arr);
return 0;
}


Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.Arrays;
class GFG {
public static int firstMissingPositive(int[] nums,
int n)
{
Arrays.sort(nums);
int ans = 1;
for (int i = 0; i < n; i++) {
if (nums[i] == ans)
ans++;
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
int n = arr.length;
int ans = firstMissingPositive(arr, n);
System.out.println(ans);
}
}


Python3
# Python code for the same approach
from functools import cmp_to_key
 
def cmp(a, b):
    return (a - b)
 
def firstMissingPositive(nums):
 
    nums.sort(key = cmp_to_key(cmp))
    ans = 1
    for i in range(len(nums)):
     
        if(nums[i] == ans):
            ans += 1
 
    return ans
 
# driver code
arr = [-1, 0, 8, 1]
print(firstMissingPositive(arr))
 
# This code is contributed by shinjanpatra


Javascript


输出
The smallest positive missing number is 1

请注意,此方法会修改原始数组。我们可以更改隔离数组中元素的符号以获取相同的元素集。但是我们仍然松散了元素的顺序。如果我们想保持原始数组不变,那么我们可以创建数组的副本并在临时数组上运行此方法。

另一种方法:在这个问题中,我们创建了一个充满 0 的列表,其大小与给定数组的 max() 值相同。现在,每当我们在原始数组中遇到任何正值时,我们都会将列表的索引值更改为 1。因此,完成后,我们只需遍历修改后的列表,我们遇到的第一个 0,它的 (索引值 + 1) 应该是我们的答案,因为Python中的索引从 0 开始。

以下是上述方法的实现:

C++

// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the first missing positive
// number from the given unsorted array
int firstMissingPos(int A[], int n)
{
 
    // To mark the occurrence of elements
    bool present[n + 1] = { false };
 
    // Mark the occurrences
    for (int i = 0; i < n; i++) {
 
        // Only mark the required elements
        // All non-positive elements and
        // the elements greater n + 1 will never
        // be the answer
        // For example, the array will be {1, 2, 3}
        // in the worst case and the result
        // will be 4 which is n + 1
        if (A[i] > 0 && A[i] <= n)
            present[A[i]] = true;
    }
 
    // Find the first element which didn't
    // appear in the original array
    for (int i = 1; i <= n; i++)
        if (!present[i])
            return i;
 
    // If the original array was of the
    // type {1, 2, 3} in its sorted form
    return n + 1;
}
 
// Driver code
int main()
{
 
    int A[] = { 0, 10, 2, -10, -20 };
    int size = sizeof(A) / sizeof(A[0]);
    cout << firstMissingPos(A, size);
}
 
// This code is contributed by gp6

Java

// Java Program to find the smallest
// positive missing number
import java.util.*;
public class GFG {
 
    static int solution(int[] A)
    {
        int n = A.length;
      //Let this 1e6 be the maximum elemnt provided in the array;
          int N=1000010;
 
        // To mark the occurrence of elements
        boolean[] present = new boolean[N];
           
          int maxele=Integer.MIN_VALUE;
 
        // Mark the occurrences
        for (int i = 0; i < n; i++) {
 
            // Only mark the required elements
            // All non-positive elements and
            // the elements greater n + 1 will never
            // be the answer
            // For example, the array will be {1, 2, 3}
            // in the worst case and the result
            // will be 4 which is n + 1
            if (A[i] > 0 && A[i] <= n)
                present[A[i]] = true;
           
          //find the maximum element so that if all the elements are in order can directly return the next number
          maxele=Math.max(maxele,A[i]);
        }
 
        // Find the first element which didn't
        // appear in the original array
        for (int i = 1; i < N; i++)
            if (!present[i])
                return i;
 
        // If the original array was of the
        // type {1, 2, 3} in its sorted form
        return maxele + 1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int A[] = { 0, 10, 2, -10, -20 };
        System.out.println(solution(A));
      int arr[]={-2,-1,0,1,2,3,4};
      System.out.println(solution(arr));
    }
}
// This code is contributed by Arava Sai Teja

Python3

# Python3 Program to find the smallest
# positive missing number
 
 
def solution(A):  # Our original array
 
    m = max(A)  # Storing maximum value
    if m < 1:
 
        # In case all values in our array are negative
        return 1
    if len(A) == 1:
 
        # If it contains only one element
        return 2 if A[0] == 1 else 1
    l = [0] * m
    for i in range(len(A)):
        if A[i] > 0:
            if l[A[i] - 1] != 1:
 
                # Changing the value status at the index of our list
                l[A[i] - 1] = 1
    for i in range(len(l)):
 
        # Encountering first 0, i.e, the element with least value
        if l[i] == 0:
            return i + 1
            # In case all values are filled between 1 and m
    return i + 2
 
# Driver Code
A = [0, 10, 2, -10, -20]
print(solution(A))

C#

// C# Program to find the smallest
// positive missing number
using System;
using System.Linq;
 
class GFG {
    static int solution(int[] A)
    {
        // Our original array
 
        int m = A.Max(); // Storing maximum value
 
        // In case all values in our array are negative
        if (m < 1) {
            return 1;
        }
        if (A.Length == 1) {
 
            // If it contains only one element
            if (A[0] == 1) {
                return 2;
            }
            else {
                return 1;
            }
        }
        int i = 0;
        int[] l = new int[m];
        for (i = 0; i < A.Length; i++) {
            if (A[i] > 0) {
                // Changing the value status at the index of
                // our list
                if (l[A[i] - 1] != 1) {
                    l[A[i] - 1] = 1;
                }
            }
        }
 
        // Encountering first 0, i.e, the element with least
        // value
        for (i = 0; i < l.Length; i++) {
            if (l[i] == 0) {
                return i + 1;
            }
        }
 
        // In case all values are filled between 1 and m
        return i + 2;
    }
 
    // Driver code
    public static void Main()
    {
        int[] A = { 0, 10, 2, -10, -20 };
        Console.WriteLine(solution(A));
    }
}
 
// This code is contributed by PrinciRaj1992

PHP

 0)
        {
            if ($l[$A[$i] - 1] != 1)
            {
                 
                //Changing the value status at the index of our list
                $l[$A[$i] - 1] = 1;
            }
        }
    }
    for ($i = 0;$i < sizeof($l); $i++)
    {
          
        //Encountering first 0, i.e, the element with least value
        if ($l[$i] == 0)
            return $i+1;
    }
            //In case all values are filled between 1 and m
    return $i+2;   
}
 
// Driver Code
$A = array(0, 10, 2, -10, -20);
echo solution($A);
return 0;
?>

Javascript


输出
1

另一种方法:

  • 最小的正整数是 1。首先我们将检查数组中是否存在 1。如果它不存在,那么 1 就是答案。
  • 如果存在,则再次遍历数组。最大可能的答案是N+1其中N 是数组的大小。当数组包含从 1 到 N 的所有元素时会发生这种情况。当我们遍历数组时,如果我们发现任何小于 1 或大于 N 的数字,那么我们会将其更改为 1。这不会改变任何东西,因为答案会总是在 1 到 N+1 之间。现在我们的数组有从 1 到 N 的元素。
  • 现在,对于每个第 i 个数字,将arr[ (arr[i]-1) ] 增加 N 。但这会使值增加超过 N。因此,我们将通过arr[(arr[i]-1)%N]访问数组。我们所做的是对于每个值,我们将该索引处的值增加 N。
  • 我们现在将找到哪个索引的值小于 N+1。那么i+1就是我们的答案。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function for finding the first missing positive number
 
int firstMissingPositive(int arr[], int n)
{
    int ptr = 0;
 
    // Check if 1 is present in array or not
    for (int i = 0; i < n; i++) {
        if (arr[i] == 1) {
            ptr = 1;
            break;
        }
    }
 
    // If 1 is not present
    if (ptr == 0)
        return 1;
 
    // Changing values to 1
    for (int i = 0; i < n; i++)
        if (arr[i] <= 0 || arr[i] > n)
            arr[i] = 1;
 
    // Updating indices according to values
    for (int i = 0; i < n; i++)
        arr[(arr[i] - 1) % n] += n;
 
    // Finding which index has value less than n
    for (int i = 0; i < n; i++)
        if (arr[i] <= n)
            return i + 1;
 
    // If array has values from 1 to n
    return n + 1;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    int ans = firstMissingPositive(arr, n);
 
    cout << ans;
 
    return 0;
}

C

// C program for the above approach
#include 
#include 
 
// Function for finding the first
// missing positive number
int firstMissingPositive(int arr[], int n)
{
    int ptr = 0;
 
    // Check if 1 is present in array or not
    for(int i = 0; i < n; i++)
    {
        if (arr[i] == 1)
        {
            ptr = 1;
            break;
        }
    }
 
    // If 1 is not present
    if (ptr == 0)
        return 1;
 
    // Changing values to 1
    for(int i = 0; i < n; i++)
        if (arr[i] <= 0 || arr[i] > n)
            arr[i] = 1;
 
    // Updating indices according to values
    for(int i = 0; i < n; i++)
        arr[(arr[i] - 1) % n] += n;
 
    // Finding which index has value less than n
    for(int i = 0; i < n; i++)
        if (arr[i] <= n)
            return i + 1;
 
    // If array has values from 1 to n
    return n + 1;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int ans = firstMissingPositive(arr, n);
     
    printf("%d", ans);
     
    return 0;
}
 
// This code is contributed by shailjapriya

Java

// Java program for the above approach
import java.util.Arrays;
 
class GFG{
 
// Function for finding the first
// missing positive number
static int firstMissingPositive(int arr[], int n)
{
    int ptr = 0;
 
    // Check if 1 is present in array or not
    for(int i = 0; i < n; i++)
    {
        if (arr[i] == 1)
        {
            ptr = 1;
            break;
        }
    }
 
    // If 1 is not present
    if (ptr == 0)
        return (1);
 
    // Changing values to 1
    for(int i = 0; i < n; i++)
        if (arr[i] <= 0 || arr[i] > n)
            arr[i] = 1;
 
    // Updating indices according to values
    for(int i = 0; i < n; i++)
        arr[(arr[i] - 1) % n] += n;
 
    // Finding which index has value less than n
    for(int i = 0; i < n; i++)
        if (arr[i] <= n)
            return (i + 1);
 
    // If array has values from 1 to n
    return (n + 1);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
    int n = arr.length;
    int ans = firstMissingPositive(arr, n);
     
    System.out.println(ans);
}
}
 
// This code is contributed by shailjapriya

Python3

# Python3 program for the above approach
 
# Function for finding the first missing
# positive number
def firstMissingPositive(arr, n):
     
    ptr = 0
     
    # Check if 1 is present in array or not
    for i in range(n):
        if arr[i] == 1:
            ptr = 1
            break
         
    # If 1 is not present
    if ptr == 0:
        return(1)
         
    # Changing values to 1
    for i in range(n):
        if arr[i] <= 0 or arr[i] > n:
            arr[i] = 1
             
    # Updating indices according to values
    for i in range(n):
        arr[(arr[i] - 1) % n] += n
         
    # Finding which index has value less than n
    for i in range(n):
        if arr[i] <= n:
            return(i + 1)
 
    # If array has values from 1 to n
    return(n + 1)
 
# Driver Code
 
# Given array
A = [ 2, 3, -7, 6, 8, 1, -10, 15 ]
 
# Size of the array
N = len(A)
 
# Function call
print(firstMissingPositive(A, N))
 
# This code is contributed by shailjapriya

C#

// C# program for the above approach
using System;
using System.Linq;
   
class GFG{
 
// Function for finding the first missing
// positive number    
static int firstMissingPositive(int[] arr, int n)
{
    int ptr = 0;
     
    // Check if 1 is present in array or not
    for(int i = 0; i < n; i++)
    {
        if (arr[i] == 1)
        {
            ptr = 1;
            break;
        }
    }
   
    // If 1 is not present
    if (ptr == 0)
        return 1;
   
    // Changing values to 1
    for(int i = 0; i < n; i++)
        if (arr[i] <= 0 || arr[i] > n)
            arr[i] = 1;
   
    // Updating indices according to values
    for(int i = 0; i < n; i++)
        arr[(arr[i] - 1) % n] += n;
   
    // Finding which index has value less than n
    for(int i = 0; i < n; i++)
        if (arr[i] <= n)
            return i + 1;
   
    // If array has values from 1 to n
    return n + 1;
}
 
// Driver code
public static void Main()
{
    int[] A = { 2, 3, -7, 6, 8, 1, -10, 15 };
    int n = A.Length;
    int ans = firstMissingPositive(A, n);
     
    Console.WriteLine(ans);
}
}
 
// This code is contributed by shailjapriya

Javascript


输出:

4

时间复杂度: O(n)
空间复杂度: O(1)

另一种方法:

  1. 遍历数组,忽略大于n小于1的元素。
  2. 遍历时检查 a[i]!=a[a[i]-1] 条件是否成立。
  3. 如果上述条件为真,则交换 a[i], a[a[i] – 1] && 直到 a[i] != a[a[i] – 1] 条件将失败。
  4. 遍历数组并检查是否 a[i] != i + 1 然后返回 i + 1。
  5. 如果所有都等于它的索引,则返回 n+1。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function for finding the first
// missing positive number
int firstMissingPositive(int arr[], int n)
{
     
    // Loop to traverse the whole array
    for (int i = 0; i < n; i++) {
       
        // Loop to check boundary
        // condition and for swapping
        while (arr[i] >= 1 && arr[i] <= n
               && arr[i] != arr[arr[i] - 1]) {
            swap(arr[i], arr[arr[i] - 1]);
        }
    }
   
    // Checking any element which
    // is not equal to i+1
    for (int i = 0; i < n; i++) {
        if (arr[i] != i + 1) {
            return i + 1;
        }
    }
   
    // Nothing is present return last index
    return n + 1;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    int ans = firstMissingPositive(arr, n);
 
    cout << ans;
 
    return 0;
}
// This code is contributed by Harsh kedia

Java

// Java program for the above approach
import java.util.Arrays;
 
class GFG{
 
// Function for finding the first
// missing positive number
static int firstMissingPositive(int arr[], int n)
{
 
    // Check if 1 is present in array or not
    for(int i = 0; i < n; i++)
    {
       
      // Loop to check boundary
      // condition and for swapping
      while (arr[i] >= 1 && arr[i] <= n
             && arr[i] != arr[arr[i] - 1]) {
         
        int temp=arr[arr[i]-1];
            arr[arr[i]-1]=arr[i];
            arr[i]=temp;
      }
    }
 
    // Finding which index has value less than n
    for(int i = 0; i < n; i++)
        if (arr[i] != i + 1)
            return (i + 1);
 
    // If array has values from 1 to n
    return (n + 1);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = {2, 3, -7, 6, 8, 1, -10, 15 };
    int n = arr.length;
    int ans = firstMissingPositive(arr, n);
     
    System.out.println(ans);
}
}
 
// This code is contributed by mohit kumar 29.

Python3

# Python program for the above approach
# Function for finding the first
# missing positive number
def firstMissingPositive(arr, n):
 
    # Loop to traverse the whole array
    for i in range(n):
       
        # Loop to check boundary
        # condition and for swapping
        while (arr[i] >= 1 and arr[i] <= n
               and arr[i] != arr[arr[i] - 1]):
            temp = arr[i]
            arr[i] = arr[arr[i] - 1]
            arr[temp - 1] = temp
     
    # Checking any element which
    # is not equal to i+1
    for i in range(n):
        if (arr[i] != i + 1):
            return i + 1
         
    # Nothing is present return last index
    return n + 1
 
# Driver code
arr = [ 2, 3, -7, 6, 8, 1, -10, 15 ];
n = len(arr)
ans = firstMissingPositive(arr, n)
print(ans)
 
# This code is contributed by shivanisinghss2110

C#

// C# program for the above approach
using System;
public class GFG{
 
  // Function for finding the first
  // missing positive number
  static int firstMissingPositive(int[] arr, int n)
  {
 
    // Check if 1 is present in array or not
    for(int i = 0; i < n; i++)
    {
 
      // Loop to check boundary
      // condition and for swapping
      while (arr[i] >= 1 && arr[i] <= n
             && arr[i] != arr[arr[i] - 1]) {
 
        int temp = arr[arr[i] - 1];
        arr[arr[i] - 1] = arr[i];
        arr[i] = temp;
      }
    }
 
    // Finding which index has value less than n
    for(int i = 0; i < n; i++)
      if (arr[i] != i + 1)
        return (i + 1);
 
    // If array has values from 1 to n
    return (n + 1);
  }
 
  // Driver Code
 
  static public void Main ()
  {
 
    int[] arr = {2, 3, -7, 6, 8, 1, -10, 15 };
    int n = arr.Length;
    int ans = firstMissingPositive(arr, n);
 
    Console.WriteLine(ans);
  }
}
 
// This code is contributed by ab2127

Javascript


输出
4

另一种使用小而清晰的代码的简单方法。

直觉:因为我们要计算第一个缺失的正整数,最小的正整数是1。

因此,取 ans=1 并遍历数组一次并检查 nums[i]==ans 是否(意味着我们正在检查从 1 到缺失数字的值)。

通过迭代该条件是否满足 nums[i]==ans 然后将 ans 递增 1 并再次检查相同的条件直到数组的大小。

在对数组进行一次扫描后,我们将丢失的数字存储在 ans 变量中。

现在将该 ans 作为 int 中的返回类型返回给函数。

上述直觉的代码实现如下:

C++

#include 
using namespace std;
int firstMissingPositive(vector& nums) {
sort(nums.begin(),nums.end());
int ans=1;
for(int i=0;iarr={-1,0,8,1};
cout << firstMissingPositive(arr);
return 0;
}

Java

/*package whatever //do not write package name here */
import java.io.*;
import java.util.Arrays;
class GFG {
public static int firstMissingPositive(int[] nums,
int n)
{
Arrays.sort(nums);
int ans = 1;
for (int i = 0; i < n; i++) {
if (nums[i] == ans)
ans++;
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
int n = arr.length;
int ans = firstMissingPositive(arr, n);
System.out.println(ans);
}
}

Python3

# Python code for the same approach
from functools import cmp_to_key
 
def cmp(a, b):
    return (a - b)
 
def firstMissingPositive(nums):
 
    nums.sort(key = cmp_to_key(cmp))
    ans = 1
    for i in range(len(nums)):
     
        if(nums[i] == ans):
            ans += 1
 
    return ans
 
# driver code
arr = [-1, 0, 8, 1]
print(firstMissingPositive(arr))
 
# This code is contributed by shinjanpatra

Javascript


输出
2

时间复杂度: O(n*log(n))

空间复杂度: O(1)