Skip to content

Instantly share code, notes, and snippets.

@summit87
Created January 8, 2019 10:52
Show Gist options
  • Save summit87/064fb18ee319dd9bbbed5fc4c9f4c9ac to your computer and use it in GitHub Desktop.
Save summit87/064fb18ee319dd9bbbed5fc4c9f4c9ac to your computer and use it in GitHub Desktop.
package app;
public class GetPairInRotatedArray {
public static void main(String[] args) {
int[] a = { 11, 15, 26, 38, 9, 10 };
int hi = getIndex(a, 0, a.length - 1);
int low = hi + 1;
System.out.println(isSumExist(a, hi, low, 35));
}
private static boolean isSumExist(int[] a, int hIndex, int lIndex, int key) {
while (lIndex != hIndex) {
if (lIndex >= a.length) {
break;
}
int sum1 = a[hIndex] + a[lIndex];
if (sum1 == key) {
return true;
}
if (sum1 > key) {
hIndex--;
} else if (sum1 < key) {
lIndex++;
}
if (hIndex < 0) {
hIndex = a.length - 1;
}
}
return false;
}
private static int getIndex(int[] a, int left, int right) {
int m = (left + right) / 2;
if (left == right) {
return -1;
}
if (m >= 0 && m < a.length && a[m] > a[m + 1]) {
return m;
}
if (m > left && a[m] < a[m - 1]) {
return m - 1;
}
if (a[m] < a[right]) {
return getIndex(a, left, m - 1);
}
return getIndex(a, m + 1, right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment