📜  从自然数中删除给定的整数后,第K个最小元素|套装2

📅  最后修改于: 2021-05-04 12:45:10             🧑  作者: Mango

给定大小为’n’的数组arr []和正整数k。考虑一系列自然数,并从中删除arr [0],arr [1],arr [2],…,arr [n-1]。现在的任务是在剩余的自然数集中找到第k个最小的数。

例子:

Input : arr[] = { 1 } and k = 1.
Output: 2
Natural numbers are {1, 2, 3, 4, .... }
After removing {1}, we get {2, 3, 4, ...}.
Now, K-th smallest element = 2.

Input : arr[] = {1, 3}, k = 4.
Output : 6
First 5 Natural number {1, 2, 3, 4, 5, 6,  .. }
After removing {1, 3}, we get {2, 4, 5, 6, ... }.

本文讨论了2种方法。

这篇文章讨论了另一种方法。

算法:

  1. 开始遍历数组,因为i的范围是0到N-1
  2. 如果arr [i] <= k,然后递增k。其他突破遍历数组的其余部分
  3. 获得的k是最终答案
C++
// C++ program to find the K-th smallest element
// after removing some integers from natural number.
#include 
using namespace std;
  
// Return the K-th smallest element.
int ksmallest(int arr[], int n, int k)
{
    for (int i = 0; i < n; i++) {
        if (arr[i] <= k)
            k++;
        else
            break;
    }
    return k;
}
  
// Driven Program
int main()
{
    int k = 1;
    int arr[] = { 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << ksmallest(arr, n, k);
    return 0;
}


Java
// Java program to find the
// K-th smallest element
// after removing some 
// integers from natural number.
class GFG
{
  
// Return the K-th 
// smallest element.
static int ksmallest(int arr[], 
                     int n, int k)
{
    for (int i = 0; i < n; i++) 
    {
        if (arr[i] <= k)
            k++;
        else
            break;
    }
    return k;
}
  
// Driver Code
public static void main(String args[])
{
    int k = 1;
    int arr[] = { 1 };
    int n = arr.length;
    System.out.println(ksmallest(arr, n, k));
}
}
  
// This code is contributed 
// by Arnab Kundu


Python3
# Python3 program to find 
# the K-th smallest element 
# after removing some integers
# from natural number.
  
# Return the K-th 
# smallest element.
def ksmallest(arr, n, k):
    for i in range(n): 
        if (arr[i] <= k):
            k = k + 1;
        else:
            break;
    return k;
  
# Driver Code
k = 1;
arr = [1];
n = len(arr);
print(ksmallest(arr, n, k));
      
# This code is contributed by mits


C#
// C# program to find the
// K-th smallest element
// after removing some 
// integers from natural number.
using System;
  
class GFG
{
// Return the K-th 
// smallest element.
  
static int ksmallest(int []arr, 
                     int n, int k)
{
    for (int i = 0; i < n; i++) 
    {
        if (arr[i] <= k)
            k++;
        else
            break;
    }
    return k;
}
  
// Driver Code
static public void Main ()
{
    int k = 1;
    int []arr = { 1 };
    int n = arr.Length;
    Console.WriteLine(ksmallest(arr, 
                                n, k));
}
}
  
// This code is contributed @ajit


PHP


输出:
2