Skip to content

Instantly share code, notes, and snippets.

@tolinwei
Created September 22, 2016 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolinwei/04139f48f454f83c6de880e4ef2f11b3 to your computer and use it in GitHub Desktop.
Save tolinwei/04139f48f454f83c6de880e4ef2f11b3 to your computer and use it in GitHub Desktop.
/**
* Created by linwei on 9/20/16.
*/
public class PivotNumber {
/* Test case:
3 4 5 2 (6) 7 8 9 return 6's index 4
4 2 6 (5) 7 8 9 return 5's index 3
4 2 6 5 3 9 return -1
*/
public int get(int[] array) {
int pivotIndex = 0;
int max = array[0];
int i = 1;
while (i < array.length) {
// System.out.println("pivotIndex: " + pivotIndex + ", array[" + i + "]: " + array[i] + ", max: " + max);
if (array[i] > max) { // of course it's larger than array[pivotIndex]
max = array[i]; // update the max
i++;
} else if (array[i] > array[pivotIndex]) {
i++;
} else if (array[i] < array[pivotIndex]) {
if (i == array.length - 1) {
return -1;
} else {
i++;
while (i < array.length && array[i] <= max) {
i++;
}
if (i < array.length) {
pivotIndex = i;
} else {
return -1;
}
}
}
}
if (i == array.length) return pivotIndex;
else return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment