-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathRecursion_AllIndexesOfANumber.java
51 lines (33 loc) · 1.24 KB
/
Recursion_AllIndexesOfANumber.java
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
public class Recursion_AllIndexesOfANumber {
public static int[] indexBtao(int input[], int x, int startIndex){
//if startindex reaches the end return empty array.
if(startIndex == input.length){
int[] ans = new int[0];
return ans;
}
//recursion baazi
int[] smallAns = indexBtao(input,x, startIndex+1);
//if the number is found at startIndex
if (input[startIndex] == x){
int[] ans = new int[smallAns.length +1];
//return startIndex;
//shift elements to accomodate the starting index
ans[0] = startIndex;
for(int i = 0; i<smallAns.length; i++){
ans[i+1] = smallAns[i];
}
return ans;
}else{
return smallAns;
}
}
public static int[] allIndexes(int input[], int x) {
/* Your class should be named Solution
* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
return indexBtao(input,x,0);
}
}