Search an Element in an array
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Search an Element in an array相关的知识,希望对你有一定的参考价值。
Given an integer array and an element x, find if element is present in array or not. If element is present, then print index of its first occurrence. Else print -1.
Input:
First line contains an integer, the number of test cases ‘T‘ Each test case should contain an integer, size of array ‘N‘ in the first line. In the second line Input the integer elements of the array in a single line separated by space. Element X should be inputted in the third line after entering the elements of array.
Output:
print the output in a separate line returning the index of the element X.If element not present then print -1.
Constraints:
1 <= T <= 100
1 <= N <= 100
1 <= Arr[i] <= 100
Example:
Input:
1
4
1 2 3 4
3
Output:
2
Explanation:
There is one test case with array as {1, 2, 3 4} and element to be searched as 3. Since 3 is present at index 2, output is 2
我的代码实现:
#include <iostream> using namespace std; int main() { int T; cin>>T; while(T--){ int N,j,X,index=-1; cin>>N; int *Arr=new int[N]; for(j=0;j<N;j++) { cin>>Arr[j]; } cin>>X; for(j=0;j<N;j++) { if(Arr[j]==X) { index=j; break; } } cout<<index<<endl; } return 0; }
以上是关于Search an Element in an array的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解
703. Kth Largest Element in a Stream/215. Kth Largest Element in an Array/
codeforces A. In Search of an Easy Problem
How do I remove a particular element from an array in JavaScript?