Saturday, January 29, 2022

All Indices Of Element In Array




public class AllIndicesOfElementInArray {
public static void main(String[] args) {

int[] arr = new int[]{2, 3, 3, 4, 3};
int element = 3;
int[] ans = allIndices(arr, 3, 0, 0);

for (int x : ans) {
System.out.println(x);
}
}

private static int[] allIndices(int[] arr, int ele, int idx, int fsf) {
if (idx == arr.length)
return new int[fsf];

if (arr[idx] == ele)
fsf += 1;

int[] faith = allIndices(arr, ele, idx + 1, fsf);

if (arr[idx] == ele) {
faith[fsf - 1] = idx;
}

return faith;
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...