|
| 1 | +--- |
| 2 | +comments: true |
| 3 | +difficulty: easy |
| 4 | +# Follow `Topics` tags |
| 5 | +tags: |
| 6 | + - Array |
| 7 | + - Binary Search |
| 8 | +--- |
| 9 | + |
| 10 | +# [704. Binary Search](https://leetcode.com/problems/binary-search/description/) |
| 11 | + |
| 12 | +## Description |
| 13 | + |
| 14 | +You are given a sorted array of integers `nums` (in ascending order) and an integer `target`. |
| 15 | +Write a function to find the `target` in the array. If it exists, return its index; otherwise, return `-1`. |
| 16 | + |
| 17 | +Your solution must have a time complexity of **O(log n)**. |
| 18 | + |
| 19 | +**Example 1:** |
| 20 | +``` |
| 21 | +Input: nums = [-1,1,4,6,9,15], target = 9 |
| 22 | +Output: 4 |
| 23 | +Explanation: 9 exists in nums and its index is 4 |
| 24 | +``` |
| 25 | + |
| 26 | +**Example 2:** |
| 27 | +``` |
| 28 | +Input: nums = [-1,1,4,6,9,15], target = 3 |
| 29 | +Output: -1 |
| 30 | +Explanation: 3 does not exist in nums so return -1 |
| 31 | +``` |
| 32 | + |
| 33 | +**Constraints:** |
| 34 | + |
| 35 | +* `1 <= nums.length <= 10^4` |
| 36 | +* `-10^4 < nums[i], target < 10^4` |
| 37 | +* All the integers in `nums` are unique. |
| 38 | +* `nums` is sorted in ascending order. |
| 39 | + |
| 40 | +## Solution |
| 41 | + |
| 42 | + |
| 43 | +```java |
| 44 | +class Solution { |
| 45 | + public int search(int[] nums, int target) { |
| 46 | + int left = 0, right = nums.length - 1; |
| 47 | + while (left <= right) { |
| 48 | + int mid = (left + right) / 2; |
| 49 | + if (nums[mid] == target) { |
| 50 | + return mid; |
| 51 | + } else if (nums[mid] < target) { |
| 52 | + left = mid + 1; |
| 53 | + } else { |
| 54 | + right = mid - 1; |
| 55 | + } |
| 56 | + } |
| 57 | + return -1; |
| 58 | + } |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | +```python |
| 63 | +class Solution: |
| 64 | + def search(self, nums: list[int], target: int) -> int: |
| 65 | + left, right = 0, len(nums) - 1 |
| 66 | + while left <= right: |
| 67 | + mid = (left + right) // 2 |
| 68 | + if nums[mid] == target: |
| 69 | + return mid |
| 70 | + elif nums[mid] < target: |
| 71 | + left = mid + 1 |
| 72 | + else: |
| 73 | + right = mid - 1 |
| 74 | + return -1 |
| 75 | +``` |
| 76 | + |
| 77 | +## Complexity |
| 78 | + |
| 79 | +- Time complexity: $$O(log n)$$ |
| 80 | +<!-- Add time complexity here, e.g. $$O(n)$$ --> |
| 81 | + |
| 82 | +- Space complexity: $$O(1)$$ |
| 83 | +<!-- Add space complexity here, e.g. $$O(n)$$ --> |
| 84 | + |
0 commit comments