问题一:将一个具有n个元素的数组向右旋转i个位置。
EXAMPLE:
Input: 将(1, 2, 3, 4, 5, 6, 7, 8, 9)旋转3个位置
Output: (7, 8, 9, 1, 2, 3, 4, 5, 6)
问题二:(Cracking the coding interview 9.3)Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originally sorted in increasing order.
EXAMPLE:
Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)
Output: 8 (the index of 5 in the array)
思路:仍然采用二分法进行搜索,搜索的时候多加一些判断。
int FindRotatedSortedArray(const int nVal, const int *pArr, const int nlength) { int idxL = 0;; int idxR = nlength - 1; int idxM = (idxL + idxR) / 2; while (idxR >= idxL) { idxM = (idxL + idxR) / 2; if (nVal == pArr[idxM]) return idxM; if (pArr[idxL] < pArr[idxR])// arr not rotated. 10 ,,,, 15 ,,,, 20 { if (pArr[idxM] > nVal) //search left idxR = idxM - 1; else //search right idxL = idxM + 1; } else { if (pArr[idxM] < pArr[idxL] && pArr[idxM] < pArr[idxR]) // 20 ,,,, 5 ,,,, 10 { if (nVal < pArr[idxM] || nVal >= pArr[idxL]) // 20 ,(25 ,, 4), 5 ,,,, 10 idxR = idxM - 1; //search left else // 20 ,,,, 5 ,,(6),, 10 idxL = idxM + 1; // search right } else if (pArr[idxM] >= pArr[idxL] && pArr[idxM] > pArr[idxR])// 20 ,,,, 25 ,,,, 10 { if (nVal > pArr[idxM] || nVal <= pArr[idxR]) // 20 ,,,, 25 ,(30 ,, 5), 10 { idxL = idxM + 1; //search right } else // 20 ,,(23),, 25 ,,,, 10 { idxR = idxM - 1; //search left } } } } return -1; }
问题三:Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds the index of the minimum element.
EXAMPLE:
Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)
Output: 5 (the index of 1 in the array)
int FindMinimun(const int *pArr, const int nLength) { if (NULL == pArr) return -1; int idxL = 0; int idxR = nLength - 1; int idxM; while (idxL <= idxR) { if (pArr[idxL] <= pArr[idxR]) // ,,, 5, ,,, 10, ,,, return idxL; if (idxL + 1 == idxR && pArr[idxL] > pArr[idxR])// ,,, 10, 1, ,,, return idxR; idxM = (idxL + idxR)/2; if (pArr[idxM] >= pArr[idxL]) // ,,, 10, ,,, 20, ,,, 1, ,,, idxL = idxM + 1; else if (pArr[idxM] <= pArr[idxR]) // ,,, 10, ,,, 5, ,,, 20, ,,, idxR = idxM; else return -1; } return -1; }