📜  查找范围的缺失元素

📅  最后修改于: 2021-10-27 08:53:47             🧑  作者: Mango

给定一个由不同元素组成的数组 arr[0..n-1] 和一个范围 [low, high],找到一个范围内的所有数字,但不是该数组。缺少的元素应按排序顺序打印。

例子:

Input: arr[] = {10, 12, 11, 15}, 
       low = 10, high = 15
Output: 13, 14

Input: arr[] = {1, 14, 11, 51, 15}, 
       low = 50, high = 55
Output: 50, 52, 53, 54

可以有两种方法来解决这个问题。

使用排序:对数组进行排序,然后对“低”进行二分搜索。找到 low 的位置后,从该位置开始遍历数组并继续打印所有丢失的数字。

C++
// A sorting based C++ program to find missing
// elements from an array
#include 
using namespace std;
 
// Print all elements of range [low, high] that
// are not present in arr[0..n-1]
void printMissing(int arr[], int n, int low,
                  int high)
{
    // Sort the array
    sort(arr, arr + n);
 
    // Do binary search for 'low' in sorted
    // array and find index of first element
    // which either equal to or greater than
    // low.
    int* ptr = lower_bound(arr, arr + n, low);
    int index = ptr - arr;
 
    // Start from the found index and linearly
    // search every range element x after this
    // index in arr[]
    int i = index, x = low;
    while (i < n && x <= high) {
        // If x doesn't math with current element
        // print it
        if (arr[i] != x)
            cout << x << " ";
 
        // If x matches, move to next element in arr[]
        else
            i++;
 
        // Move to next element in range [low, high]
        x++;
    }
 
    // Print range elements thar are greater than the
    // last element of sorted array.
    while (x <= high)
        cout << x++ << " ";
}
 
// Driver program
int main()
{
    int arr[] = { 1, 3, 5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int low = 1, high = 10;
    printMissing(arr, n, low, high);
    return 0;
}


Java
// A sorting based Java program to find missing
// elements from an array
 
import java.util.Arrays;
 
public class PrintMissing {
    // Print all elements of range [low, high] that
    // are not present in arr[0..n-1]
    static void printMissing(int ar[], int low, int high)
    {
        Arrays.sort(ar);
        // Do binary search for 'low' in sorted
        // array and find index of first element
        // which either equal to or greater than
        // low.
        int index = ceilindex(ar, low, 0, ar.length - 1);
        int x = low;
 
        // Start from the found index and linearly
        // search every range element x after this
        // index in arr[]
        while (index < ar.length && x <= high) {
            // If x doesn't math with current element
            // print it
            if (ar[index] != x) {
                System.out.print(x + " ");
            }
 
            // If x matches, move to next element in arr[]
            else
                index++;
            // Move to next element in range [low, high]
            x++;
        }
 
        // Print range elements thar are greater than the
        // last element of sorted array.
        while (x <= high) {
            System.out.print(x + " ");
            x++;
        }
    }
 
    // Utility function to find ceil index of given element
    static int ceilindex(int ar[], int val, int low, int high)
    {
 
        if (val < ar[0])
            return 0;
        if (val > ar[ar.length - 1])
            return ar.length;
 
        int mid = (low + high) / 2;
        if (ar[mid] == val)
            return mid;
        if (ar[mid] < val) {
            if (mid + 1 < high && ar[mid + 1] >= val)
                return mid + 1;
            return ceilindex(ar, val, mid + 1, high);
        }
        else {
            if (mid - 1 >= low && ar[mid - 1] < val)
                return mid;
            return ceilindex(ar, val, low, mid - 1);
        }
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
        int arr[] = { 1, 3, 5, 4 };
        int low = 1, high = 10;
        printMissing(arr, low, high);
    }
}
 
// This code is contributed by Rishabh Mahrsee


Python
# Python library for binary search
from bisect import bisect_left
 
# A sorting based C++ program to find missing
# elements from an array
 
# Print all elements of range [low, high] that
# are not present in arr[0..n-1]
 
def printMissing(arr, n, low, high):
     
    # Sort the array
    arr.sort()
     
    # Do binary search for 'low' in sorted
    # array and find index of first element
    # which either equal to or greater than
    # low.
    ptr = bisect_left(arr, low)
    index = ptr
     
    # Start from the found index and linearly
    # search every range element x after this
    # index in arr[]
    i = index
    x = low
    while (i < n and x <= high):
    # If x doesn't math with current element
    # print it
        if(arr[i] != x):
            print(x, end =" ")
 
    # If x matches, move to next element in arr[]
        else:
            i = i + 1
    # Move to next element in range [low, high]
        x = x + 1
 
    # Print range elements thar are greater than the
    # last element of sorted array.
    while (x <= high):
        print(x, end =" ")
        x = x + 1
 
 
# Driver code
 
arr = [1, 3, 5, 4]
n = len(arr)
low = 1
high = 10
printMissing(arr, n, low, high);
 
# This code is contributed by YatinGupta


C#
// A sorting based Java program to
// find missing elements from an array
using System;
 
class GFG {
 
    // Print all elements of range
    // [low, high] that are not
    // present in arr[0..n-1]
    static void printMissing(int[] ar,
                             int low, int high)
    {
        Array.Sort(ar);
 
        // Do binary search for 'low' in sorted
        // array and find index of first element
        // which either equal to or greater than
        // low.
        int index = ceilindex(ar, low, 0,
                              ar.Length - 1);
        int x = low;
 
        // Start from the found index and linearly
        // search every range element x after this
        // index in arr[]
        while (index < ar.Length && x <= high) {
            // If x doesn't math with current
            // element print it
            if (ar[index] != x) {
                Console.Write(x + " ");
            }
 
            // If x matches, move to next
            // element in arr[]
            else
                index++;
 
            // Move to next element in
            // range [low, high]
            x++;
        }
 
        // Print range elements thar
        // are greater than the
        // last element of sorted array.
        while (x <= high) {
            Console.Write(x + " ");
            x++;
        }
    }
 
    // Utility function to find
    // ceil index of given element
    static int ceilindex(int[] ar, int val,
                         int low, int high)
    {
        if (val < ar[0])
            return 0;
        if (val > ar[ar.Length - 1])
            return ar.Length;
 
        int mid = (low + high) / 2;
        if (ar[mid] == val)
            return mid;
        if (ar[mid] < val) {
            if (mid + 1 < high && ar[mid + 1] >= val)
                return mid + 1;
            return ceilindex(ar, val, mid + 1, high);
        }
        else {
            if (mid - 1 >= low && ar[mid - 1] < val)
                return mid;
            return ceilindex(ar, val, low, mid - 1);
        }
    }
 
    // Driver Code
    static public void Main()
    {
        int[] arr = { 1, 3, 5, 4 };
        int low = 1, high = 10;
        printMissing(arr, low, high);
    }
}
 
// This code is contributed
// by Sach_Code


C++14
// An array based C++ program
// to find missing elements from
// an array
#include 
using namespace std;
 
// Print all elements of range
// [low, high] that are not present
// in arr[0..n-1]
void printMissing(
    int arr[], int n,
    int low, int high)
{
    // Create boolean array of size
    // high-low+1, each index i representing
    // whether (i+low)th element found or not.
    bool points_of_range[high - low + 1] = { false };
 
    for (int i = 0; i < n; i++) {
        // if ith element of arr is in
        // range low to high then mark
        // corresponding index as true in array
        if (low <= arr[i] && arr[i] <= high)
            points_of_range[arr[i] - low] = true;
    }
 
    // Traverse through the range and
    // print all elements  whose value
    // is false
    for (int x = 0; x <= high - low; x++) {
        if (points_of_range[x] == false)
            cout << low + x << " ";
    }
}
 
// Driver program
int main()
{
    int arr[] = { 1, 3, 5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int low = 1, high = 10;
    printMissing(arr, n, low, high);
    return 0;
}
 
// This code is contributed by Shubh Bansal


Java
// An array based Java program
// to find missing elements from
// an array
 
import java.util.Arrays;
 
public class Print {
    // Print all elements of range
    // [low, high] that are not present
    // in arr[0..n-1]
    static void printMissing(
        int arr[], int low,
        int high)
    {
        // Create boolean array of
        // size high-low+1, each index i
        // representing whether (i+low)th
        // element found or not.
        boolean[] points_of_range = new boolean
            [high - low + 1];
 
        for (int i = 0; i < arr.length; i++) {
            // if ith element of arr is in
            // range low to high then mark
            // corresponding index as true in array
            if (low <= arr[i] && arr[i] <= high)
                points_of_range[arr[i] - low] = true;
        }
 
        // Traverse through the range and print all
        // elements whose value is false
        for (int x = 0; x <= high - low; x++) {
            if (points_of_range[x] == false)
                System.out.print((low + x) + " ");
        }
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
        int arr[] = { 1, 3, 5, 4 };
        int low = 1, high = 10;
        printMissing(arr, low, high);
    }
}
 
// This code is contributed by Shubh Bansal


Python3
# An array-based Python3 program to
# find missing elements from an array
 
# Print all elements of range
# [low, high] that are not
# present in arr[0..n-1]
def printMissing(arr, n, low, high):
 
    # Create boolean list of size
    # high-low+1, each index i
    # representing whether (i+low)th
    # element found or not.
    points_of_range = [False] * (high-low+1)
     
    for i in range(n) :
        # if ith element of arr is in range
        # low to high then mark corresponding
        # index as true in array
        if ( low <= arr[i] and arr[i] <= high ) :
            points_of_range[arr[i]-low] = True
 
    # Traverse through the range
    # and print all elements  whose value
    # is false
    for x in range(high-low+1) :
        if (points_of_range[x]==False) :
            print(low+x, end = " ")
 
# Driver Code
arr = [1, 3, 5, 4]
n = len(arr)
low, high = 1, 10
printMissing(arr, n, low, high)
 
# This code is contributed
# by Shubh Bansal


C#
// An array based C# program
// to find missing elements from
// an array
using System;
 
class GFG{
 
// Print all elements of range
// [low, high] that are not present
// in arr[0..n-1]
static void printMissing(int[] arr, int n,
                         int low, int high)
{
     
    // Create boolean array of size
    // high-low+1, each index i representing
    // whether (i+low)th element found or not.
      bool[] points_of_range = new bool[high - low + 1];
       
      for(int i = 0; i < high - low + 1; i++)
          points_of_range[i] = false;
 
    for(int i = 0; i < n; i++)
    {
         
        // If ith element of arr is in
        // range low to high then mark
        // corresponding index as true in array
        if (low <= arr[i] && arr[i] <= high)
            points_of_range[arr[i] - low] = true;
    }
 
    // Traverse through the range and
    // print all elements  whose value
    // is false
    for(int x = 0; x <= high - low; x++)
    {
        if (points_of_range[x] == false)
            Console.Write("{0} ", low + x);
    }
}
 
// Driver code
public static void Main()
{
    int[] arr = { 1, 3, 5, 4 };
    int n = arr.Length;
    int low = 1, high = 10;
     
    printMissing(arr, n, low, high);
}
}
 
// This code is contributed by subhammahato348


Javascript


C++
// A hashing based C++ program to find missing
// elements from an array
#include 
using namespace std;
 
// Print all elements of range [low, high] that
// are not present in arr[0..n-1]
void printMissing(int arr[], int n, int low,
                  int high)
{
    // Insert all elements of arr[] in set
    unordered_set s;
    for (int i = 0; i < n; i++)
        s.insert(arr[i]);
 
    // Traverse throught the range an print all
    // missing elements
    for (int x = low; x <= high; x++)
        if (s.find(x) == s.end())
            cout << x << " ";
}
 
// Driver program
int main()
{
    int arr[] = { 1, 3, 5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int low = 1, high = 10;
    printMissing(arr, n, low, high);
    return 0;
}


Java
// A hashing based Java program to find missing
// elements from an array
 
import java.util.Arrays;
import java.util.HashSet;
 
public class Print {
    // Print all elements of range [low, high] that
    // are not present in arr[0..n-1]
    static void printMissing(int ar[], int low, int high)
    {
        HashSet hs = new HashSet<>();
 
        // Insert all elements of arr[] in set
        for (int i = 0; i < ar.length; i++)
            hs.add(ar[i]);
 
        // Traverse throught the range an print all
        // missing elements
        for (int i = low; i <= high; i++) {
            if (!hs.contains(i)) {
                System.out.print(i + " ");
            }
        }
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
        int arr[] = { 1, 3, 5, 4 };
        int low = 1, high = 10;
        printMissing(arr, low, high);
    }
}
 
// This code is contributed by Rishabh Mahrsee


Python3
# A hashing based Python3 program to
# find missing elements from an array
 
# Print all elements of range
# [low, high] that are not
# present in arr[0..n-1]
def printMissing(arr, n, low, high):
 
    # Insert all elements of
    # arr[] in set
    s = set(arr)
 
    # Traverse through the range
    # and print all missing elements
    for x in range(low, high + 1):
        if x not in s:
            print(x, end = ' ')
 
# Driver Code
arr = [1, 3, 5, 4]
n = len(arr)
low, high = 1, 10
printMissing(arr, n, low, high)
 
# This code is contributed
# by SamyuktaSHegde


C#
// A hashing based C# program to
// find missing elements from an array
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Print all elements of range
    // [low, high] that are not
    // present in arr[0..n-1]
    static void printMissing(int[] arr, int n,
                             int low, int high)
    {
        // Insert all elements of arr[] in set
        HashSet s = new HashSet();
        for (int i = 0; i < n; i++) {
            s.Add(arr[i]);
        }
 
        // Traverse throught the range
        // an print all missing elements
        for (int x = low; x <= high; x++)
            if (!s.Contains(x))
                Console.Write(x + " ");
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 1, 3, 5, 4 };
        int n = arr.Length;
        int low = 1, high = 10;
        printMissing(arr, n, low, high);
    }
}
 
// This code is contributed by ihritik


输出:

2 6 7 8 9 10

使用数组:创建一个布尔数组,其中每个索引将表示数组中是否存在第 (i+low) 个元素。标记给定范围内并出现在数组中的所有元素。一旦给定范围内的所有数组项在数组中都被标记为真,我们遍历布尔数组并打印所有值为假的元素。

C++14

// An array based C++ program
// to find missing elements from
// an array
#include 
using namespace std;
 
// Print all elements of range
// [low, high] that are not present
// in arr[0..n-1]
void printMissing(
    int arr[], int n,
    int low, int high)
{
    // Create boolean array of size
    // high-low+1, each index i representing
    // whether (i+low)th element found or not.
    bool points_of_range[high - low + 1] = { false };
 
    for (int i = 0; i < n; i++) {
        // if ith element of arr is in
        // range low to high then mark
        // corresponding index as true in array
        if (low <= arr[i] && arr[i] <= high)
            points_of_range[arr[i] - low] = true;
    }
 
    // Traverse through the range and
    // print all elements  whose value
    // is false
    for (int x = 0; x <= high - low; x++) {
        if (points_of_range[x] == false)
            cout << low + x << " ";
    }
}
 
// Driver program
int main()
{
    int arr[] = { 1, 3, 5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int low = 1, high = 10;
    printMissing(arr, n, low, high);
    return 0;
}
 
// This code is contributed by Shubh Bansal

Java

// An array based Java program
// to find missing elements from
// an array
 
import java.util.Arrays;
 
public class Print {
    // Print all elements of range
    // [low, high] that are not present
    // in arr[0..n-1]
    static void printMissing(
        int arr[], int low,
        int high)
    {
        // Create boolean array of
        // size high-low+1, each index i
        // representing whether (i+low)th
        // element found or not.
        boolean[] points_of_range = new boolean
            [high - low + 1];
 
        for (int i = 0; i < arr.length; i++) {
            // if ith element of arr is in
            // range low to high then mark
            // corresponding index as true in array
            if (low <= arr[i] && arr[i] <= high)
                points_of_range[arr[i] - low] = true;
        }
 
        // Traverse through the range and print all
        // elements whose value is false
        for (int x = 0; x <= high - low; x++) {
            if (points_of_range[x] == false)
                System.out.print((low + x) + " ");
        }
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
        int arr[] = { 1, 3, 5, 4 };
        int low = 1, high = 10;
        printMissing(arr, low, high);
    }
}
 
// This code is contributed by Shubh Bansal

蟒蛇3

# An array-based Python3 program to
# find missing elements from an array
 
# Print all elements of range
# [low, high] that are not
# present in arr[0..n-1]
def printMissing(arr, n, low, high):
 
    # Create boolean list of size
    # high-low+1, each index i
    # representing whether (i+low)th
    # element found or not.
    points_of_range = [False] * (high-low+1)
     
    for i in range(n) :
        # if ith element of arr is in range
        # low to high then mark corresponding
        # index as true in array
        if ( low <= arr[i] and arr[i] <= high ) :
            points_of_range[arr[i]-low] = True
 
    # Traverse through the range
    # and print all elements  whose value
    # is false
    for x in range(high-low+1) :
        if (points_of_range[x]==False) :
            print(low+x, end = " ")
 
# Driver Code
arr = [1, 3, 5, 4]
n = len(arr)
low, high = 1, 10
printMissing(arr, n, low, high)
 
# This code is contributed
# by Shubh Bansal

C#

// An array based C# program
// to find missing elements from
// an array
using System;
 
class GFG{
 
// Print all elements of range
// [low, high] that are not present
// in arr[0..n-1]
static void printMissing(int[] arr, int n,
                         int low, int high)
{
     
    // Create boolean array of size
    // high-low+1, each index i representing
    // whether (i+low)th element found or not.
      bool[] points_of_range = new bool[high - low + 1];
       
      for(int i = 0; i < high - low + 1; i++)
          points_of_range[i] = false;
 
    for(int i = 0; i < n; i++)
    {
         
        // If ith element of arr is in
        // range low to high then mark
        // corresponding index as true in array
        if (low <= arr[i] && arr[i] <= high)
            points_of_range[arr[i] - low] = true;
    }
 
    // Traverse through the range and
    // print all elements  whose value
    // is false
    for(int x = 0; x <= high - low; x++)
    {
        if (points_of_range[x] == false)
            Console.Write("{0} ", low + x);
    }
}
 
// Driver code
public static void Main()
{
    int[] arr = { 1, 3, 5, 4 };
    int n = arr.Length;
    int low = 1, high = 10;
     
    printMissing(arr, n, low, high);
}
}
 
// This code is contributed by subhammahato348

Javascript


输出:

2 6 7 8 9 10

Use Hashing:创建一个哈希表并将所有数组项插入到哈希表中。一旦所有项目都在哈希表中,遍历范围并打印所有丢失的元素。

C++

// A hashing based C++ program to find missing
// elements from an array
#include 
using namespace std;
 
// Print all elements of range [low, high] that
// are not present in arr[0..n-1]
void printMissing(int arr[], int n, int low,
                  int high)
{
    // Insert all elements of arr[] in set
    unordered_set s;
    for (int i = 0; i < n; i++)
        s.insert(arr[i]);
 
    // Traverse throught the range an print all
    // missing elements
    for (int x = low; x <= high; x++)
        if (s.find(x) == s.end())
            cout << x << " ";
}
 
// Driver program
int main()
{
    int arr[] = { 1, 3, 5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int low = 1, high = 10;
    printMissing(arr, n, low, high);
    return 0;
}

Java

// A hashing based Java program to find missing
// elements from an array
 
import java.util.Arrays;
import java.util.HashSet;
 
public class Print {
    // Print all elements of range [low, high] that
    // are not present in arr[0..n-1]
    static void printMissing(int ar[], int low, int high)
    {
        HashSet hs = new HashSet<>();
 
        // Insert all elements of arr[] in set
        for (int i = 0; i < ar.length; i++)
            hs.add(ar[i]);
 
        // Traverse throught the range an print all
        // missing elements
        for (int i = low; i <= high; i++) {
            if (!hs.contains(i)) {
                System.out.print(i + " ");
            }
        }
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
        int arr[] = { 1, 3, 5, 4 };
        int low = 1, high = 10;
        printMissing(arr, low, high);
    }
}
 
// This code is contributed by Rishabh Mahrsee

蟒蛇3

# A hashing based Python3 program to
# find missing elements from an array
 
# Print all elements of range
# [low, high] that are not
# present in arr[0..n-1]
def printMissing(arr, n, low, high):
 
    # Insert all elements of
    # arr[] in set
    s = set(arr)
 
    # Traverse through the range
    # and print all missing elements
    for x in range(low, high + 1):
        if x not in s:
            print(x, end = ' ')
 
# Driver Code
arr = [1, 3, 5, 4]
n = len(arr)
low, high = 1, 10
printMissing(arr, n, low, high)
 
# This code is contributed
# by SamyuktaSHegde

C#

// A hashing based C# program to
// find missing elements from an array
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Print all elements of range
    // [low, high] that are not
    // present in arr[0..n-1]
    static void printMissing(int[] arr, int n,
                             int low, int high)
    {
        // Insert all elements of arr[] in set
        HashSet s = new HashSet();
        for (int i = 0; i < n; i++) {
            s.Add(arr[i]);
        }
 
        // Traverse throught the range
        // an print all missing elements
        for (int x = low; x <= high; x++)
            if (!s.Contains(x))
                Console.Write(x + " ");
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 1, 3, 5, 4 };
        int n = arr.Length;
        int low = 1, high = 10;
        printMissing(arr, n, low, high);
    }
}
 
// This code is contributed by ihritik

输出:

2 6 7 8 9 10

哪种方法更好?
第一种方法的时间复杂度为 O(nLogn + k) 其中 k 是缺失元素的数量(注意,如果数组很小且范围很大,k 可能会大于 nLogn)
第二个和第三个解决方案的时间复杂度是 O(n + (high-low+1))。

如果给定的数组几乎包含范围内的所有元素,即 n 接近 (high-low+1) 的值,那么第二种和第三种方法肯定更好,因为没有 Log n 因子。但是如果 n 比范围小得多,那么第一种方法更好,因为它不需要额外的空间进行散列。我们还可以修改第一种方法以将相邻的缺失元素打印为范围以节省时间。例如,如果缺少 50、51、52、53、54、59,我们可以在第一种方法中将它们打印为 50-54、59。如果允许以这种方式打印,第一种方法只需要 O(n Log n) 时间。在第二个和第三个解决方案中,第二个解决方案更好,因为第二个解决方案的最坏情况时间复杂度优于第三个。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程