给定数组arr []和整数K ,任务是从给定数组中找到第K个奇数元素。
例子:
Input: arr[] = {1, 2, 3, 4, 5}, K = 2
Output: 3
3 is the 2nd odd element from the given array
Input: arr[] = {2, 4, 6, 18}, K = 5
Output: -1
There are no odd elements in the given array.
方法:逐个遍历数组元素,对于遇到的每个奇数元素,将值k减1 。如果k的值等于0,则打印当前元素。遍历整个数组后,如果k的值> 0,则打印-1,因为数组中奇数元素的总数小于
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the kth odd element
// from the array
int kthOdd(int arr[], int n, int k)
{
// Traverse the array
for (int i = 0; i <= n; i++)
{
// If current element is odd
if ((arr[i] % 2) == 1)
k--;
// If kth odd element is found
if (k == 0)
return arr[i];
}
// Total odd elements in the array are < k
return -1;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr)/sizeof(arr[0]);
int k = 2;
cout << (kthOdd(arr, n, k));
return 0;
}
// This code is contributed by jit_t
Java
// Java implementation of the approach
public class GFG {
// Function to return the kth odd element
// from the array
static int kthOdd(int arr[], int n, int k)
{
// Traverse the array
for (int i = 0; i < n; i++) {
// If current element is odd
if (arr[i] % 2 == 1)
k--;
// If kth odd element is found
if (k == 0)
return arr[i];
}
// Total odd elements in the array are < k
return -1;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = arr.length;
int k = 2;
System.out.print(kthOdd(arr, n, k));
}
}
Python3
# Python3 implementation of the approach
# Function to return the kth odd
# element from the array
def kthOdd (arr, n, k):
# Traverse the array
for i in range(n):
# If current element is odd
if (arr[i] % 2 == 1):
k -= 1;
# If kth odd element is found
if (k == 0):
return arr[i];
# Total odd elements in the
# array are < k
return -1;
# Driver code
arr = [ 1, 2, 3, 4, 5 ];
n = len(arr);
k = 2;
print(kthOdd(arr, n, k));
# This code is contributed by mits
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the kth odd element
// from the array
static int kthOdd(int []arr, int n, int k)
{
// Traverse the array
for (int i = 0; i < n; i++)
{
// If current element is odd
if (arr[i] % 2 == 1)
k--;
// If kth odd element is found
if (k == 0)
return arr[i];
}
// Total odd elements in the array are < k
return -1;
}
// Driver code
public static void Main()
{
int []arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
int k = 2;
Console.WriteLine(kthOdd(arr, n, k));
}
}
// This code is contributed by SoM15242
PHP
Javascript
输出:
3