May LeetCoding Challenge12 之 二分搜索

本题有两种解法,

第一种为暴力法,线性搜索。

但因为题目为递增序列中查找一个数,自然会有第二种方法:二分搜索法。

二分搜索既可以调用JAVA自身的函数 Arrays.binarySearch(),也可以自己手写。

   int a[] = new int[] {1, 3, 4, 6, 8, 9};  
        int x1 = Arrays.binarySearch(a, 5);  
        int x2 = Arrays.binarySearch(a, 4);  
        int x3 = Arrays.binarySearch(a, 0);  
        int x4 = Arrays.binarySearch(a, 10);

/*
1.找到的情况下:如果key在数组中,则返回搜索值的索引。
2.找不到的情况下:
 [1] 搜索值不是数组元素,且在数组范围内,从1开始计数,得“ - 插入点索引值”;
 [2] 搜索值不是数组元素,且大于数组内元素,索引值为 – (length + 1);
 [3] 搜索值不是数组元素,且小于数组内元素,索引值为 – 1。
*/

x1 = -4; x2 = 2; x3 = -1; x4 = -7;

JAVA

class Solution {
    public int singleNonDuplicate(int[] nums) {
        int res = nums[0];
        for(int i = 1; i < nums.length; i += 2){
            res -= nums[i];
            res += nums[i+1];
        }
        return res;
    }
}
class Solution {
    public int singleNonDuplicate(int[] nums) {
        int left = 0;
        int right = nums.length-1;
        while(left < right){
            int mid = left + (right-left)/2;
            if((mid%2) == 1) mid--;
            if(nums[mid] == nums[mid+1]) left = mid+2;
            else right = mid;
        }
        return nums[right];
    }
}

Python3

class Solution:
    def singleNonDuplicate(self, nums: List[int]) -> int:
        res = nums[0]
        for i in range(1, len(nums), 2):
            res -= nums[i]
            res += nums[i+1]
        return res
class Solution:
    def singleNonDuplicate(self, nums: List[int]) -> int:
        left = 0
        right = len(nums)-1
        while left < right:
            mid = left + (right-left)//2
            if mid%2 == 1:
                mid -= 1
            if nums[mid] == nums[mid+1]:
                left = mid+2
            else:
                right = mid
        return nums[right]
原文地址:https://www.cnblogs.com/yawenw/p/12877168.html