|
@@ -0,0 +1,48 @@
|
|
|
+package com.sf.leetcode;
|
|
|
+
|
|
|
+public class Solution_704 {
|
|
|
+
|
|
|
+ public static void main(String[] args) {
|
|
|
+ int[] nums = new int[]{-1, 0, 3, 5, 9, 12};
|
|
|
+ int search = new Solution_704().search(nums, 9);
|
|
|
+ System.out.println(search);
|
|
|
+ }
|
|
|
+
|
|
|
+ public int search(int[] nums, int target) {
|
|
|
+ int n = nums.length;
|
|
|
+ int start = 0;
|
|
|
+ int end = n - 1;
|
|
|
+ while (start <= end) {
|
|
|
+ int mid = start + ((end - start) >> 1);
|
|
|
+ if (nums[mid] > target) {
|
|
|
+ end = mid - 1;
|
|
|
+ } else if (nums[mid] < target) {
|
|
|
+ start = mid + 1;
|
|
|
+ } else {
|
|
|
+ return mid;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return -1;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 用递归实现?
|
|
|
+ public int search1(int[] nums, int target) {
|
|
|
+ return searchByRec(nums, 0, nums.length - 1, target);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 如果要改造成递归 要把每次变化的参数加进来 成为新的函数
|
|
|
+ public int searchByRec(int[] nums, int start, int end, int target) {
|
|
|
+ // 递归规律 递归的出口
|
|
|
+ if (start > end) return -1;
|
|
|
+
|
|
|
+ int mid = start + ((end - start) >> 1);
|
|
|
+ if (nums[mid] == target) {
|
|
|
+ return mid;
|
|
|
+ }
|
|
|
+ if (nums[mid] > target) {
|
|
|
+ return searchByRec(nums, start, mid - 1, target);
|
|
|
+ }
|
|
|
+ // nums[mid] < target
|
|
|
+ return searchByRec(nums, mid + 1, end, target);
|
|
|
+ }
|
|
|
+}
|