{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

704. Binary Search

\n", "
\n", "\n", "\n", "

Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.

\n", "\n", "


\n", "Example 1:

\n", "\n", "
Input: nums = [-1,0,3,5,9,12], target = 9\n",
    "Output: 4\n",
    "Explanation: 9 exists in nums and its index is 4\n",
    "\n",
    "
\n", "\n", "

Example 2:

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

 

\n", "\n", "

Note:

\n", "\n", "
    \n", "\t
  1. You may assume that all elements in nums are unique.
  2. \n", "\t
  3. n will be in the range [1, 10000].
  4. \n", "\t
  5. The value of each element in nums will be in the range [-9999, 9999].
  6. \n", "
\n", "\n", "\n", "

 

\n", "Source \n", "
\n", "\n", "

Code

" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def binary_search(nums, target):\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Check

" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nums = [-1,0,3,5,9,12]\n", "target = 9\n", "binary_search(nums, target)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nums = [-1,0,3,5,9,12]\n", "target = 2\n", "binary_search(nums, target)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Follow up:

\n", "

Solve it both iteratively and recursively. Solve it using built-in methods too.

" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "def binary_search(nums, target):\n", " pass" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 1 }