📜  奇偶序列中的第k个数

📅  最后修改于: 2021-04-28 18:32:32             🧑  作者: Mango

给定两个数字n和k,在由n构成的奇偶序列中找到第k个数字。奇偶序列首先包含从1到n的所有奇数,然后包含集合1到n的所有偶数。

Examples :
Input :  n = 5, k = 3
Output : 5
In this example, the Odd-Even  is
{1, 3, 5, 2, 4}. 
The third number in sequence is 5.

天真的方法:

第一种方法是简单地创建一个奇偶序列,然后在其中找到第k个元素。

C++
// CPP program to find k-th
// element in the Odd-Even
// sequence.
#include 
using namespace std;
 
int findK(int n, int k)
{
    vector a;
     
    // insert all the odd
    // numbers from 1 to n.
    for (int i = 1; i < n; i++)
        if (i % 2 == 1)
            a.push_back(i);
     
    // insert all the even
    // numbers from 1 to n.
    for (int i = 1; i < n; i++)
        if (i % 2 == 0)
            a.push_back(i);
     
    return (a[k - 1]);
}
 
// Driver code
int main()
{
    long n = 10, k = 3;
    cout << findK(n, k) << endl;
    return 0;
}


Java
// Java program to find k-th
// element in the Odd-Even
// sequence.
import java.util.*;
 
class GFG{
static int findK(int n, int k)
{
    ArrayList a = new ArrayList(n);
     
    // insert all the odd
    // numbers from 1 to n.
    for (int i = 1; i < n; i++)
        if (i % 2 == 1)
            a.add(i);
     
    // insert all the even
    // numbers from 1 to n.
    for (int i = 1; i < n; i++)
        if (i % 2 == 0)
            a.add(i);
     
    return (a.get(k - 1));
}
 
// Driver code
public static void main(String[] args)
{
    int n = 10, k = 3;
    System.out.println(findK(n, k));
}
}
// This code is contributed by mits


Python3
# Python3 code to find
# k-th element in the
# Odd-Even sequence.
 
def findK (n, k ):
    a = list()
     
    # insert all the odd
    # numbers from 1 to n.
    i = 1
    while i < n:
        a.append(i)
        i = i + 2
     
    # insert all the even
    # numbers from 1 to n.
    i = 2
    while i < n:
        a.append(i)
        i = i + 2
         
    return (a[k - 1])
 
# Driver code
n = 10
k = 3
print(findK(n, k))
 
# This code is contributed
# by "Sharad_Bhardwaj".


C#
// C# program to find k-th
// element in the Odd-Even
// sequence.
using System;
using System.Collections;
 
class GFG{
static int findK(int n, int k)
{
    ArrayList a = new ArrayList(n);
     
    // insert all the odd
    // numbers from 1 to n.
    for (int i = 1; i < n; i++)
        if (i % 2 == 1)
            a.Add(i);
     
    // insert all the even
    // numbers from 1 to n.
    for (int i = 1; i < n; i++)
        if (i % 2 == 0)
            a.Add(i);
     
    return (int)(a[k - 1]);
}
 
// Driver code
static void Main()
{
    int n = 10, k = 3;
    Console.WriteLine(findK(n, k));
}
}
// This code is contributed by mits


PHP


Javascript


输出 :

5

上述方法的时间复杂度为O(n),对于O(1)方法,请阅读此处讨论的方法。