📜  删除所有奇数后,找到范围[1,n]中的第k个最小数

📅  最后修改于: 2021-04-24 18:01:44             🧑  作者: Mango

给定两个整数nk ,任务是在删除范围中的所有奇数后从范围[1,n]中找到第k最小元素。
例子:

方法:由于所有奇数均已删除,因此现在仅保留偶数,即2、4、6、8…..
现在,第k最小元素将始终为2 * k
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the kth smallest
// element from the range [1, n] after
// removing all the odd elements
int kthSmallest(int n, int k)
{
    return (2 * k);
}
 
// Driver code
int main()
{
    int n = 8, k = 4;
    cout << kthSmallest(n, k);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG {
 
    // Function to return the kth smallest
    // element from the range [1, n] after
    // removing all the odd elements
    static int kthSmallest(int n, int k)
    {
        return (2 * k);
    }
 
    // Driver code
    public static void main(String args[])
    {
        int n = 8, k = 4;
        System.out.print(kthSmallest(n, k));
    }
}


Python3
# Python3 implementation of the approach
 
# Function to return the kth smallest
# element from the range [1, n] after
# removing all the odd elements
def kthSmallest(n, k):
    return 2 * k
 
# Driver code
n = 8; k = 4
print(kthSmallest(n, k))
 
# This code is contributed
# by Shrikant13


C#
// C# implementation of the approach
using System;
class GFG {
 
    // Function to return the kth smallest
    // element from the range [1, n] after
    // removing all the odd elements
    static int kthSmallest(int n, int k)
    {
        return (2 * k);
    }
 
    // Driver code
    public static void Main()
    {
        int n = 8, k = 4;
        Console.WriteLine(kthSmallest(n, k));
    }
}
 
// This code is contributed by Code_Mech


PHP


Javascript


输出:
8

时间复杂度: O(1)