其他分享
首页 > 其他分享> > May LeetCoding Challenge12 之 二分搜索

May LeetCoding Challenge12 之 二分搜索

作者:互联网

本题有两种解法,

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

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

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]

 

标签:LeetCoding,right,nums,May,res,mid,Challenge12,int,left
来源: https://www.cnblogs.com/yawenw/p/12877168.html