首页 > 代码库 > CC150 9.3
CC150 9.3
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 find(int[] ints, int low, int high, int t) { if (low > high) return -1; // not found int mid = (low + high) / 2; if (ints[mid] == t) return mid; // found if (ints[mid] < t) { // if max/min point is left side, t is in [mid-high] or [left-max] // if max/min point is right side, t is in [mid-max] if (isMPointLeft(ints, low, mid)) { if (ints[high] < t) { return find(ints, low, mid - 1); } else { return find(ints, mid + 1, high); } } else { return find(ints, mid + 1, high); } } else { // if max/min point is left side, t is in [min-mid] // if max/min point is right side, t is in [low - mid] or [min - high] if (isMPointLeft(ints, low, mid)) { return find(ints, left, mid - 1); } else { if (ints[low] > t) { return find(ints, mid + 1, high); } else { return find(ints, low, mid - 1); } } } } boolean isMPointLeft(int[]ints, int low, int mid) { return ints[low] > ints[mid]; }
CC150 9.3
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。