【LeetCode】 Binary Search 二分搜索

来源:互联网 发布:易语言dnf辅助源码模板 编辑:程序博客网 时间:2024/09/21 06:18
  1. For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.
    If the target number does not exist in the array, return -1.
    Example :If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2

(1)Java

// version 1: with template//template:①用while易死循环,若写得好可以给面试加分 while (start + 1 < end):相邻就退出,不容易死循环;至于最后:依据题目要找first/last position,相应的作出判断谁先谁后。【相应先判断:if (nums[start/last] == target) 】③取中位数写法好处:若整数太大,start+end可能溢出。class Solution {    /**     * @param nums: The integer array.     * @param target: Target to find.     * @return: The first position of target. Position starts from 0.     */    public int binarySearch(int[] nums, int target) {        if (nums == null || nums.length == 0) {            return -1;        }        int start = 0, end = nums.length - 1;        while (start + 1 < end) {            int mid = start + (end - start) / 2 ③;            if (nums[mid] == target) {                end = mid;            } else if (nums[mid] < target) {                start = mid;                // or start = mid + 1            } else {                end = mid;                // or end = mid - 1            }        }        if (nums[start] == target) {            return start;        }        if (nums[end] == target) {            return end;        }        return -1;    }}// version 2: class Solution {    public int binarySearch(int[] nums, int target) {        if (nums == null || nums.length == 0) {            return -1;        }        int start = 0, end = nums.length - 1;        while (start < end) {            int mid = start + (end - start) / 2;            if (nums[mid] == target) {                end = mid;            } else if (nums[mid] < target) {                start = mid + 1;            } else {                end = mid - 1;            }        }        if (nums[start] == target) {            return start;        }        return -1;    }}

(2)C++

#include <vector>using namespace std;class Solution {    public:    /**     * @param array source array     * @param target target to search     * @return the first occurrence position of target      */    int binarySearch(vector<int> &A, int target) {        if (A.size() == 0) {            return -1;        }        int start = 0;        int end = A.size() - 1;        int mid;        while (start + 1 < end) {            mid = start + (end - start) / 2;            if (A[mid] == target) {                end = mid;            } else if (A[mid] < target) {                start = mid;            } else if (A[mid] > target) {                end = mid;            }        }        if (A[start] == target) {            return start;        }        if (A[end] == target) {            return end;        }        return -1;    }};