LeetCode Question Bank------704.Binary Search

LeetCode Question Bank------704.Binary Search (Java)

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

Example

输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4

Question analysis

Given the target value target, array […], find whether target exists in the array

answer

Method 1: Violent solution

class Solution {
    
    
    public int search(int[] nums, int target) {
    
    
    for (int i = 0; i < nums.length; i++) {
    
    
                if(nums[i] == target){
    
    
                    return i;
                }
            }
    return -1;
    }
}
  • Execution time: 1 ms, beats 10.49% of all Java submissions

  • Memory consumption: 42.3 MB, beats 5.03% of users among all Java submissions

Idea:

Starting from the first element, compare the query in sequence

Method 2: Binary sorting

public int search(int[] nums, int target) {
    
    
        int low = 0, high = nums.length - 1;
        while (low <= high) {
    
    
            int mid = (high - low) / 2 + low;
            int num = nums[mid];
            if (num == target) {
    
    
                return mid;
            } else if (num > target) {
    
    
                high = mid - 1;
            } else {
    
    
                low = mid + 1;
            }
        }
        return -1;
    }
  • Execution time: 0 ms, beat 100.00% of users across all Java submissions

  • Memory consumption: 42.2 MB, beats 11.94% of users among all Java submissions

Idea:

Since the array is sorted in ascending order, it is more convenient to use the binary method. Check whether the middle value element is target. If it is greater than target, let it high = mid - 1; if it is less than target, let it low = mid + 1continue to check the relationship between the current middle value element and target.

Guess you like

Origin blog.csdn.net/weixin_44176393/article/details/123842464