[LeetCode Brush Questions-Java/Python] Binary Search

704. Binary Search

topic

Topic link
Given an ordered (ascending) integer array nums with n elements and a target value target, write a function to search the target in nums, and return the subscript if the target value exists, otherwise return -1

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 appears in nums with subscript 4

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

accomplish

class Solution {
    
    
    public int search(int[] nums,int target) {
    
    
        if(target<nums[0]||target>nums[nums.length-1]) // nums.length
            return -1;
        int left=0;
        int right=nums.length - 1;
        while(left<=right){
    
    
            int mid=(left+right)/2; 
            //mid = left + ((right - left) >> 1);
            if (nums[mid]==target)
                return mid;
            else if (nums[mid]<target)
                left=mid+1;
            else if (nums[mid]>target)
                right=mid-1;
        }
        return -1;
    }
}
class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        left = 0;
        right = len(nums)-1;
        while left<=right:
            mid=(right+left)/2
            if nums[mid]>target:
                right=mid-1  
            elif nums[mid]<target:
                left=mid+1 
            else:
                return middle 
        return -1 

Summarize

  • Ordered array, no duplicate elements -> binary search
  • [left, right] ,while (left <= right) ,right=middle - 1 # left=right时, [left, right]有意义
  • [left, right),right=nums.length,while (left < right) ,right=middle

35. Search insertion position

topic

Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position where it will be inserted in order.

Please use an algorithm with time complexity O(log n).

Input: nums = [1,3,5,6], target = 5
Output: 2

Input: nums = [1,3,5,6], target = 2
Output: 1

Input: nums = [1,3,5,6], target = 7
Output: 4

accomplish

  • Does not exist, return right+1
class Solution {
    
    
    public int searchInsert(int[] nums, int target) {
    
    
        int left=0;
        int right=nums.length - 1;
        while(left<=right){
    
    
            int mid=(left+right)/2; 
            //mid = left + ((right - left) >> 1);
            if (nums[mid]==target)
                return mid;
            else if (nums[mid]<target)
                left=mid+1;
            else if (nums[mid]>target)
                right=mid-1;
        }
        return right+1;
    }
}

34. Find the first and last position of an element in a sorted array

topic

topic link

You are given an integer array nums in non-decreasing order, and a target value target. Please find out where the given target value starts and ends in the array.

If the target value target does not exist in the array, return [-1, -1].

You must design and implement an algorithm with time complexity O(log n) to solve this problem.

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Input: nums = [], target = 0
Output: [-1,-1]

accomplish

class Solution {
    
    
    public int[] searchRange(int[] nums, int target) {
    
    
        int index=binarySearch(nums,target);
        if(index==-1)
            return new int[] {
    
    -1,-1}; //新建数组

        int left=index;
        int right=index;
        while (left-1>= 0 && nums[left-1]==nums[index]) 
			left--;
		while (right+1< nums.length && nums[right+1]==nums[index]) 
			right++;
		return new int[] {
    
    left, right};
    }

    public int binarySearch(int[] nums, int target){
    
    
        int left=0;
        int right=nums.length - 1;
        while(left<=right){
    
    
            int mid=(left+right)/2; 
            //mid = left + ((right - left) >> 1);
            if (nums[mid]==target)
                return mid;
            else if (nums[mid]<target)
                left=mid+1;
            else if (nums[mid]>target)
                right=mid-1;
        }
        return -1;
    }
}

square root of 69.x

topic

Topic link
Given a non-negative integer x, calculate and return the arithmetic square root of x.
Since the return type is an integer, only the integer part of the result is kept, and the decimal part will be discarded.
Note: Any built-in exponential functions and operators such as pow(x, 0.5) or x ** 0.5 are not allowed.

Input: x = 4
Output: 2

Input: x = 8
Output: 2
Explanation: The arithmetic square root of 8 is 2.82842…, since the return type is an integer, the decimal part will be rounded off.

accomplish

class Solution {
    
    
    public int mySqrt(int x) {
    
    
        int left=0;
        int right=x;
        int ans=-1;
        while (left<=right) {
    
    
            int mid=(left+right) / 2;
            if ((long)mid*mid<=x) {
    
    
                ans=mid;
                left=mid+1;
            } 
            else
                right=mid-1;
        }
        return ans;
    }
}

367. Efficient Perfect Squares

topic

You are given a positive integer num. Returns true if num is a perfect square, false otherwise.
A perfect square is an integer that can be written as the square of some integer. In other words, it can be written as the product of some integer and itself.
Cannot use any built-in library functions such as sqrt.

Input: num = 16
Output: true
Explanation: Returns true because 4 * 4 = 16 and 4 is an integer.

Input: num = 14
Output: false
Explanation: Returns false because 3.742 * 3.742 = 14 but 3.742 is not an integer.

accomplish

class Solution {
    
    
    public boolean isPerfectSquare(int num) {
    
    
        int left=0, right=num;
        while(left<=right){
    
    
            int mid=(left+right)/2;
            if((long)mid*mid==num)
                return true;
            else if((long)mid*mid>num)
                right=mid-1;
            else
                left=mid+1;
        }
        return false;
    }
}

Guess you like

Origin blog.csdn.net/Magnolia_He/article/details/129386470