Given an array Arr of N elements and a integer K. Your task is to print the position of first occurrence of K in the given array.
Note: Position of first element is considered as 1.
Input
- The first line contains two integers N and K.
- The second line contains N spaced integers, elements of Arr.
Constraints
- 1 <= N <= 10^6
- 1 <= K <= 10^6
- 1 <= Arr[i] <= 10^6
Output
Print the position of first occurrence of K. If K is not present in the array, print -1.
Example
Sample Input
5 16 9 7 2 16 4
Sample Output
4
Explanation
K = 16 is found in the given array at position 4.
Solution of Searching a number in java:–
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws java.lang.Exception { //your code here Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } int temp=-1; for(int i=0;i<n;i++) { if(k==arr[i]) { temp=i+1; break; } } System.out.println(temp); } }
Add a Comment