📌  相关文章
📜  找到给定序列的第K个位置元素

📅  最后修改于: 2021-05-07 00:33:38             🧑  作者: Mango

鉴于两个整数NK,任务是在K找到元素位置i,如果从1N的所有奇数为了增加随后从1所有的偶数到N递增的顺序都写下来。
例子:

方法:已知第N偶数由2 * K给出,第N奇数由2 * K – 1给出。但是,由于此处的偶数写在(N +1)/ 2个奇数之后。因此,K偶数由2 *(K –(N + 1)/ 2)给出,奇数保持与2 * K – 1相同。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the kth number
// from the required sequence
int kthNum(int n, int k)
{
 
    // Count of odd integers
    // in the sequence
    int a = (n + 1) / 2;
 
    // kth number is even
    if (k > a)
        return (2 * (k - a));
 
    // It is odd
    return (2 * k - 1);
}
 
// Driver code
int main()
{
    int n = 7, k = 7;
 
    cout << kthNum(n, k);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
 
// Function to return the kth number
// from the required sequence
static int kthNum(int n, int k)
{
 
    // Count of odd integers
    // in the sequence
    int a = (n + 1) / 2;
 
    // kth number is even
    if (k > a)
        return (2 * (k - a));
 
    // It is odd
    return (2 * k - 1);
}
 
// Driver code
public static void main(String []args)
{
    int n = 7, k = 7;
 
    System.out.println(kthNum(n, k));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
 
# Function to return the kth number
# from the required sequence
def kthNum(n, k) :
 
    # Count of odd integers
    # in the sequence
    a = (n + 1) // 2;
 
    # kth number is even
    if (k > a) :
        return (2 * (k - a));
 
    # It is odd
    return (2 * k - 1);
 
# Driver code
if __name__ == "__main__" :
 
    n = 7; k = 7;
 
    print(kthNum(n, k));
 
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
     
class GFG
{
 
// Function to return the kth number
// from the required sequence
static int kthNum(int n, int k)
{
 
    // Count of odd integers
    // in the sequence
    int a = (n + 1) / 2;
 
    // kth number is even
    if (k > a)
        return (2 * (k - a));
 
    // It is odd
    return (2 * k - 1);
}
 
// Driver code
public static void Main(String []args)
{
    int n = 7, k = 7;
 
    Console.WriteLine(kthNum(n, k));
}
}
 
// This code is contributed by PrinciRaj1992


Javascript


输出:
6

时间复杂度: O(1)