Browse Source

1117 算法

Demi 6 months ago
parent
commit
a7d8e42dc0
1 changed files with 48 additions and 0 deletions
  1. 48 0
      lesson/src/com/sf/leetcode/Solution_704.java

+ 48 - 0
lesson/src/com/sf/leetcode/Solution_704.java

@@ -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);
+    }
+}