704. Binary Search

704. Binary Search

LeetCode - The World’s Leading Online Programming Learning Platform

Binary Search

Binary search is a search algorithm that is used to find the position of a target value within a sorted array. The algorithm compares the target value to the middle element of the array, if they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half. This process is repeated until the target value is found or until the remaining half of the array is empty.

Problem Statement

Given an array of integers nums sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. The algorithm must have O(log n) runtime complexity.

Implementation

The brute force approach to solving this problem is to loop through the array. In each iteration, we check if the number at the current index of the array is equal to the target. However, this approach has a linear time complexity and is inefficient if we have a large input data.

The more efficient approach is to use the binary search algorithm. Since the array is sorted, we can divide the effective range into two subarrays in each iteration, eliminate one of the parts, and finally, we’ll find the target.

To implement binary search, we declare two pointers: a left pointer and a right pointer, and calculate the midpoint of both pointers. In the first subarray, the left pointer starts at the beginning of the array and the middle pointer ends at this subarray. In the second subarray, the middle pointer starts from the second subarray, and the right pointer ends at the end of the array.

We use a while loop to search for the target. We initialise two pointers, one at the beginning of the array and one at the end of the array. We calculate the midpoint which is equal to the average of two points. If the number in the position of the midpoint is less than the target, the target is located in the right side of the array, which means we should move the left pointer to the centre. If the number in the centre is greater than the target, depending on the same logic, we move the right pointer to the centre.

The time complexity for the binary search algorithm is O(log(n)) and the space complexity is O(1), since we don’t allocate any additional space inside the memory and we only use variables.

Conclusion

Binary search is a very efficient algorithm for searching through a sorted array. The algorithm has a logarithmic time complexity and a constant space complexity, which makes it a great choice for searching through large datasets.

code

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int left=0;
        int right=nums.size()-1;
        int middle = (right+left)/2;
        while(left <= right)
        {
            middle = (right+left)/2;
            if(nums[middle] == target)
            {
                return middle;
            }
            // [left  ... target... middle ... right]
            else if(nums[middle] > target)
            {
                right = middle-1;
            }
            else
            {
                left = middle+1;
            }
            
        }
        return -1;
    }
};
  1. array [əˈreɪ]:
  2. integer[ˈɪntɪdʒə®]
  3. sorted [ˈsɔːtɪd]
  4. ascend[əˈsend]:to rise; to go up; to climb up
  5. target[ˈtɑːɡɪt]
  6. index[ˈɪndeks]
  7. algorithm [ˈælɡərɪðəm]
  8. complexity[kəmˈpleksəti]

你可能感兴趣的:(程序员英语面试,算法,leetcode,职场和发展)