|
| 1 | +package Array; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by dheeraj on 7/17/2016. |
| 5 | + * 1 2 3 5 7 9 |
| 6 | + * ans 3 |
| 7 | + * <p> |
| 8 | + * 1- sort and do O(NlogN) |
| 9 | + * 2- counting sort O(MaxElemValue) |
| 10 | + * 3- quick select O(N) |
| 11 | + */ |
| 12 | +public class ExactlyXelemGreaterThanX { |
| 13 | + |
| 14 | + //num exists in array |
| 15 | +/* private static int getXContains(int[] ints) { |
| 16 | + int start = 0; |
| 17 | + int end = ints.length - 1; |
| 18 | + int part = partition(ints, start, end); |
| 19 | + while (part != -1 && ints[part] != ints.length-1 - part ) { |
| 20 | + if (ints[part] > ints.length-1 - part) { |
| 21 | + end = part - 1; |
| 22 | + part = partition(ints, start, end); |
| 23 | + } else { |
| 24 | + start = part + 1; |
| 25 | + part = partition(ints, start, end); |
| 26 | + } |
| 27 | + } |
| 28 | + return part == -1 ? -1 : ints[part]; |
| 29 | + }*/ |
| 30 | + |
| 31 | + //array does not contain that number |
| 32 | + private static int getXNotContains(int[] ints) { |
| 33 | + int start = 0; |
| 34 | + int end = ints.length - 1; |
| 35 | + int part = partition(ints, start, end); |
| 36 | + while (part != -1 && part + 1 != ints.length - 1 - part) { |
| 37 | + if (ints[part] > ints.length - 1 - part) { |
| 38 | + end = part - 1; |
| 39 | + part = partition(ints, start, end); |
| 40 | + } else { |
| 41 | + start = part + 1; |
| 42 | + part = partition(ints, start, end); |
| 43 | + } |
| 44 | + } |
| 45 | + return part == -1 ? -1 : part + 1; |
| 46 | + } |
| 47 | + |
| 48 | + private static int partition(int[] array, int start, int end) { |
| 49 | + if (start > end) { |
| 50 | + return -1; |
| 51 | + } |
| 52 | + int pivot = array[end]; |
| 53 | + int index = start; |
| 54 | + |
| 55 | + int temp; |
| 56 | + for (int a = start; a < end; a++) { |
| 57 | + if (array[a] < pivot) { |
| 58 | + temp = array[index]; |
| 59 | + array[index] = array[a]; |
| 60 | + array[a] = temp; |
| 61 | + index++; |
| 62 | + } |
| 63 | + } |
| 64 | + temp = array[index]; |
| 65 | + array[index] = pivot; |
| 66 | + array[end] = temp; |
| 67 | + return index; |
| 68 | + } |
| 69 | + |
| 70 | + public static void main(String[] strings) { |
| 71 | +/* |
| 72 | + int[] ints = new int[]{3, 1, 2, 7, 9, 5}; |
| 73 | +*/ |
| 74 | + int[] ints = new int[]{0, 1, 2, 7, 9, 5}; |
| 75 | + System.out.println(getXNotContains(ints)); |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments