-
Notifications
You must be signed in to change notification settings - Fork 0
/
linearSearch2.txt
62 lines (49 loc) · 1.29 KB
/
linearSearch2.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
Search an Element in an array
Given an integer array and another integer element. The task is to find if the given element is present in array or not.
Example 1:
Input:
n = 4
arr[] = {1,2,3,4}
x = 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.
Example 2:
Input:
n = 5
arr[] = {1,2,3,4,5}
x = 5
Output: 4
Explanation: For array elements
{1,2,3,4,5} element to be searched
is 5 and it is at index 4. So, the
output is 4.
Your Task:
The task is to complete the function search() which takes the array arr[], its size N and the element X as inputs and returns the index of first occurrence of X in the given array. If the element X does not exist in the array, the function should return -1.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(1).
Constraints:
1 <= n <= 10^6
0 <= arr[i] <= 10^6
0 <= x <= 10^5
solution----
class Solution
{
static int search(int arr[], int N, int X)
{
for(int i=0;i<N;i++)
{
if(arr[1]==X)
{
return 1;
}
if(arr[i]==X)
{
return i;
}
}
return -1;
}
}