leetcode_704原题链接
    image.png

    1. class Solution {
    2. public int search(int[] nums, int target) {
    3. int high = nums.length-1;
    4. int low = 0;
    5. int value = 0;
    6. while(high>=low) {
    7. value = (high+low)/2;
    8. if (nums[value]==target) {
    9. return value;
    10. }
    11. else if (nums[value]>target) {
    12. high = value-1;
    13. }
    14. else {
    15. low = value+1;
    16. }
    17. }
    18. return -1;
    19. }
    20. }

    leetcode_35原题链接
    image.png

    class Solution {
        public int searchInsert(int[] nums, int target) {
            if (nums.length==0) {
                return 0;
            }
            int l = 0;
            int r = nums.length-1;
            int mid;
            while (l<r) {
                mid = l+(r-l)/2;
                if (nums[mid]==target) {
                    return mid;
                }
                else if (nums[mid]>target) {
                    r = mid;
                }
                else {
                    l = mid+1;
                }
            }
            if (nums[l]>target) {
                return l;
            }
            else if(nums[l]<target){
                return l+1;
            }
            else {
                return l;
            }
    }
    }
    

    leetcode_162寻找峰值
    image.png

    class Solution {
        public int findPeakElement(int[] nums) {
            if (nums.length == 0) {
                return -1;
            }
            int l = 0;
            int right = nums.length-1;
            int mid ;
            while (l<right) {
                mid = l+(right-l)/2;
                if (nums[mid]>nums[mid+1]) {
                    right = mid;
                }
                else {
                    l = mid+1;
                }
            }
            return l ;
        }
    }
    

    leetcode_74搜索二维矩阵
    image.png

    class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            int m = matrix.length;
            int n = matrix[0].length;
            int l = 0;
            int r = m*n-1;
            int mid;
            while (l<r) {
                mid = l+(r-l)/2;
                if (matrix[mid/n][mid%n]==target) {
                    return true;
                }
                else if (matrix[mid/n][mid%n]>target) {
                    r = mid;
                }
                else {
                    l = mid+1;
                }
            }
            if (matrix[l/n][l%n]==target) {
                return true;
            }
            return false;
            }
    }