{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "
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",
"Example 1:
Input:\n", "\n", "nums= [-1,0,3,5,9,12],target= 9\n", "Output: 4\n", "Explanation: 9 exists innumsand its index is 4\n", "\n", "
Example 2:
\n", "\n", "Input:\n", "\n", "nums= [-1,0,3,5,9,12],target= 2\n", "Output: -1\n", "Explanation: 2 does not exist innumsso return -1\n", "
\n", "\n", "
Note:
\n", "\n", "nums are unique.n will be in the range [1, 10000].nums will be in the range [-9999, 9999].\n", "Source \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 }