public void recoverRotatedSortedArray(ArrayList<Integer> nums) {
if (nums == null || nums.size() == 0) {
return;
}
int minLoc = 0;
// binary search for min on rotated array
int start = 0;
int end = nums.size() - 1;
if (nums.get(start) < nums.get(end)) { //array not rotated
return;
}
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums.get(mid) < nums.get(end)) {
end = mid;
} else if (nums.get(mid) > nums.get(end)){
start = mid;
} else {
end--;
}
}
if (nums.get(start) < nums.get(end)) {
minLoc = start;
} else {
minLoc = end;
}
// 3 step rotate
// [start, end]
reverse(0, minLoc - 1, nums);
reverse(minLoc, nums.size() - 1, nums);
reverse(0, nums.size() - 1, nums);
}
private void reverse(int start, int end, ArrayList<Integer> nums) {
for (int i = start, j = end; i < j; i++, j--) {
int tmp = nums.get(i);
nums.set(i, nums.get(j));
nums.set(j, tmp);
}
}