mirror of
https://gitlab.com/djdietrick/docs
synced 2026-05-03 01:30:55 -04:00
Merge branch 'master' of gitlab.com:djdietrick/docs into master
This commit is contained in:
@@ -16,3 +16,33 @@ An array is a linear collection of data values that are accessible at numbered i
|
|||||||
- Removing from end: O(1)
|
- Removing from end: O(1)
|
||||||
- Copying: O(n)
|
- Copying: O(n)
|
||||||
- Traversing (including mapping, filtering, etc): O(n)
|
- Traversing (including mapping, filtering, etc): O(n)
|
||||||
|
|
||||||
|
## Common Algorithms
|
||||||
|
|
||||||
|
### Binary Search
|
||||||
|
|
||||||
|
Binary search is useful when trying to find values in a sorted array. It works by picking a middle point to check, and then dividing the array in half based on whether the value is too big or small.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def binarySearch(nums, target):
|
||||||
|
"""
|
||||||
|
:type nums: List[int]
|
||||||
|
:type target: int
|
||||||
|
:rtype: int
|
||||||
|
"""
|
||||||
|
if len(nums) == 0:
|
||||||
|
return -1
|
||||||
|
|
||||||
|
left, right = 0, len(nums) - 1
|
||||||
|
while left <= right:
|
||||||
|
mid = (left + right) // 2
|
||||||
|
if nums[mid] == target:
|
||||||
|
return mid
|
||||||
|
elif nums[mid] < target:
|
||||||
|
left = mid + 1
|
||||||
|
else:
|
||||||
|
right = mid - 1
|
||||||
|
|
||||||
|
# End Condition: left > right
|
||||||
|
return -1
|
||||||
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user