|
| 1 | +package me.ramswaroop.arrays; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by IntelliJ IDEA. |
| 5 | + * |
| 6 | + * @author: ramswaroop |
| 7 | + * @date: 8/31/15 |
| 8 | + * @time: 2:52 PM |
| 9 | + */ |
| 10 | +public class OccurrencesInSortedArray { |
| 11 | + |
| 12 | + /** |
| 13 | + * Finds the occurrences of {@param k} in sorted array {@param a} in |
| 14 | + * O(log n) time. |
| 15 | + * |
| 16 | + * @param a |
| 17 | + * @param k |
| 18 | + * @return |
| 19 | + */ |
| 20 | + public static int getOccurrencesInSortedArray(int[] a, int k) { |
| 21 | + int firstIndex = getFirstIndexOf(a, k, 0, a.length - 1); |
| 22 | + // element not found |
| 23 | + if (firstIndex == -1) { |
| 24 | + return 0; |
| 25 | + } |
| 26 | + return getLastIndexOf(a, k, firstIndex, a.length - 1) - firstIndex + 1; |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * Returns the index of first occurrence of {@param n} in array {@param a}. |
| 31 | + * |
| 32 | + * @param a |
| 33 | + * @param low |
| 34 | + * @param high |
| 35 | + * @param n |
| 36 | + * @return |
| 37 | + */ |
| 38 | + public static int getFirstIndexOf(int[] a, int n, int low, int high) { |
| 39 | + if (low <= high) { |
| 40 | + int mid = (low + high) / 2; |
| 41 | + if (a[mid] == n && (mid == 0 || a[mid - 1] < n)) { |
| 42 | + return mid; |
| 43 | + } else if (a[mid] < n) { |
| 44 | + return getFirstIndexOf(a, n, mid + 1, high); |
| 45 | + } else { |
| 46 | + return getFirstIndexOf(a, n, low, mid - 1); |
| 47 | + } |
| 48 | + } else { |
| 49 | + return -1; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Returns the index of last occurrence of {@param n} in array {@param a}. |
| 55 | + * |
| 56 | + * @param a |
| 57 | + * @param low |
| 58 | + * @param high |
| 59 | + * @param n |
| 60 | + * @return |
| 61 | + */ |
| 62 | + public static int getLastIndexOf(int[] a, int n, int low, int high) { |
| 63 | + if (low <= high) { |
| 64 | + int mid = (low + high) / 2; |
| 65 | + if (a[mid] == n && (mid == a.length - 1 || a[mid + 1] > n)) { |
| 66 | + return mid; |
| 67 | + } else if (a[mid] <= n) { |
| 68 | + return getLastIndexOf(a, n, mid + 1, high); |
| 69 | + } else { |
| 70 | + return getLastIndexOf(a, n, low, mid - 1); |
| 71 | + } |
| 72 | + } else { |
| 73 | + return -1; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + public static void main(String a[]) { |
| 78 | + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 2, 2, 2, 2, 3}, 1)); |
| 79 | + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 1, 2, 2, 2, 2, 3}, 1)); |
| 80 | + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 2, 2, 2, 2, 3}, 2)); |
| 81 | + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 2, 2, 2, 2, 3}, 3)); |
| 82 | + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 2, 2, 2, 2, 3}, 0)); |
| 83 | + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 2, 2, 2, 2, 3}, 4)); |
| 84 | + } |
| 85 | +} |
0 commit comments