|
14 | 14 | public class FindProject {
|
15 | 15 | public static void main(String[] args) {
|
16 | 16 |
|
17 |
| - int[] is=new int[]{3,5,6,7,10}; |
18 |
| - System.out.println(binary_search_xiaoyu(is,10)); |
| 17 | + int[] is=new int[]{4,5,6,7,0,1,2}; |
| 18 | + System.out.println(binary_search_33(is,4)); |
19 | 19 | // System.out.println(binarySearch(is,2));
|
20 | 20 | // Shape redRectangle = new RedShapeDecorator(new Rectangle());
|
21 | 21 | // redRectangle.doShaper();
|
@@ -213,4 +213,42 @@ public static int binary_search_xiaoyu(int[] srcArray,int des){
|
213 | 213 | }
|
214 | 214 | return -1;
|
215 | 215 | }
|
| 216 | + |
| 217 | + /** |
| 218 | + * 假设按照升序排序的数组在预先未知的某个点上进行了旋转 |
| 219 | + * ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 |
| 220 | + * 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 |
| 221 | + * @return |
| 222 | + */ |
| 223 | + public static int binary_search_33(int[] nums,int target){ |
| 224 | + if (nums.length==0) return -1; |
| 225 | + if (nums.length==1){ |
| 226 | + if (nums[0]==target){ |
| 227 | + return 0; |
| 228 | + }else{ |
| 229 | + return -1; |
| 230 | + } |
| 231 | + } |
| 232 | + int left=0; |
| 233 | + int right=nums.length-1; |
| 234 | + int middle=0; |
| 235 | + while (left<=right){ |
| 236 | + middle=(left+right)>>1; |
| 237 | + if (nums[middle]==target) return middle; |
| 238 | + if (nums[middle]>=nums[right]){ |
| 239 | + if(nums[left]<=target&&target<nums[middle]){ |
| 240 | + right = middle-1; |
| 241 | + }else{ |
| 242 | + left = middle+1; |
| 243 | + } |
| 244 | + }else{ |
| 245 | + if(nums[middle]<target&&target<=nums[right]){ |
| 246 | + left = middle+1; |
| 247 | + }else{ |
| 248 | + right = middle==0?middle:middle-1; |
| 249 | + } |
| 250 | + } |
| 251 | + } |
| 252 | + return -1; |
| 253 | + } |
216 | 254 | }
|
0 commit comments