LeetCode 704. Binary Search (二分查找)

题目标签:Binary Search

  很标准的一个二分查找,具体看code。

 

Java Solution:

Runtime:  0 ms, faster than 100 % 

Memory Usage: 39 MB, less than 90 %

完成日期:07/31/2019

关键点:二分查找

class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        
        while(left <= right) {
            int mid = left + (right - left) / 2;
            
            if(nums[mid] == target)
                return mid;
            else if(nums[mid] < target) // if mid is less than target, move to right half
                left = mid + 1;
            else // if mid is greater than target, move to left half
                right = mid - 1;
        }
        
        return -1;
    }
}

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

转载于:https://www.cnblogs.com/jimmycheng/p/11297083.html

你可能感兴趣的:(LeetCode 704. Binary Search (二分查找))