【发布时间】:2016-04-26 07:08:07
【问题描述】:
处理以下算法难题。发布问题陈述和解决方案。问题是,我们是否需要“搜索两半”部分来保证它的安全?或者当a[left] == a[mid]时,我们可以只搜索右边部分而不检查是否a[mid] == a[right] -- 因为当a[left] == a[mid]时,我认为左边的所有元素都是相等的,不能满足搜索条件来找到值。
更详细地说,我的意思是写 last else if as 是否安全,
else if (a[left] == a[mid]) {
return search(a, mid + 1, right, x);
}
问题陈述
给定一个由 n 个整数组成的排序数组,该数组已经旋转了未知次数,编写代码来查找一个元素 在数组中,你可以假设数组最初是按升序排序的
例如, 在 {15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14} 中输入 find 5 输出,8(数组中5的索引)
代码
public static int search(int a[], int left, int right, int x) {
int mid = (left + right) / 2;
if (x == a[mid]) { // Found element
return mid;
}
if (right < left) {
return -1;
}
/* While there may be an inflection point due to the rotation, either the left or
* right half must be normally ordered. We can look at the normally ordered half
* to make a determination as to which half we should search.
*/
if (a[left] < a[mid]) { // Left is normally ordered.
if (x >= a[left] && x < a[mid]) {
return search(a, left, mid - 1, x);
} else {
return search(a, mid + 1, right, x);
}
} else if (a[mid] < a[left]) { // Right is normally ordered.
if (x > a[mid] && x <= a[right]) {
return search(a, mid + 1, right, x);
} else {
return search(a, left, mid - 1, x);
}
} else if (a[left] == a[mid]) { // Left is either all repeats OR loops around (with the right half being all dups)
if (a[mid] != a[right]) { // If right half is different, search there
return search(a, mid + 1, right, x);
} else { // Else, we have to search both halves
int result = search(a, left, mid - 1, x);
if (result == -1) {
return search(a, mid + 1, right, x);
} else {
return result;
}
}
}
return -1;
}
【问题讨论】:
-
我认为这是必不可少的。你能给出完整的问题描述吗?
-
@AbuHanifa,感谢您的提问和投票,您的意思是问题陈述部分吗?这是完整的陈述。你对哪些部分感到困惑?我很高兴澄清。