mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update README.md
This commit is contained in:
parent
ff73b28ae7
commit
f2091f10d2
@ -60,7 +60,7 @@ def binary_search_recursive(array, item, higher=None, lower=0):
|
||||
|
||||
mid = (higher + lower) // 2
|
||||
|
||||
if item == array[mid]:
|
||||
if item == array[mid]:
|
||||
return mid
|
||||
|
||||
elif item < array[mid]:
|
||||
@ -72,6 +72,29 @@ def binary_search_recursive(array, item, higher=None, lower=0):
|
||||
|
||||
<br>
|
||||
|
||||
* or a slightly different version that does not carry `lower` and `higher`:
|
||||
|
||||
<br>
|
||||
|
||||
```python
|
||||
def binary_search_recursive(array, item):
|
||||
|
||||
start, end = 0, len(array)
|
||||
mid = (end - start) // 2
|
||||
|
||||
while len(array) > 0:
|
||||
if array[mid] == item:
|
||||
return True
|
||||
elif array[mid] > item:
|
||||
return binary_search_recursive(array[mid + 1:], item)
|
||||
else:
|
||||
return binary_search_recursive(array[:mid], item)
|
||||
|
||||
return False
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
---
|
||||
|
||||
### in a matrix
|
||||
@ -127,10 +150,8 @@ def sqrt(x) -> int:
|
||||
|
||||
if num > x:
|
||||
right = mid - 1
|
||||
|
||||
elif num < x:
|
||||
left = mid + 1
|
||||
|
||||
else:
|
||||
return mid
|
||||
|
||||
@ -190,3 +211,63 @@ def peak_element(nums):
|
||||
|
||||
return left
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
---
|
||||
|
||||
### find a desired sum
|
||||
|
||||
<br>
|
||||
|
||||
* if the array is sorted:
|
||||
|
||||
<br>
|
||||
|
||||
```python
|
||||
def find_pairs_max_sum(array, desired_sum):
|
||||
|
||||
i, j = 0, len(array) - 1
|
||||
|
||||
while i < j:
|
||||
this_sum = array[i] + array[j]
|
||||
if this_sum == desired_sum:
|
||||
return array[i], array[j]
|
||||
elif this_sum > desired_sum:
|
||||
j -= 1
|
||||
else:
|
||||
i += 1
|
||||
|
||||
return False
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
* if the array is not sorted, use a hash table:
|
||||
|
||||
<br>
|
||||
|
||||
```python
|
||||
def find_pairs_not_sorted(array, desired_sum):
|
||||
|
||||
lookup = {}
|
||||
|
||||
for item in array:
|
||||
key = desired_sum - item
|
||||
|
||||
if key in lookup.keys():
|
||||
lookup[key] += 1
|
||||
else:
|
||||
lookup[key] = 1
|
||||
|
||||
for item in array:
|
||||
key = desired_sum - item
|
||||
|
||||
if item in lookup.keys():
|
||||
if lookup[item] == 1:
|
||||
return (item, key)
|
||||
else:
|
||||
lookup[item] -= 1
|
||||
|
||||
return False
|
||||
```
|
||||
|
Loading…
x
Reference in New Issue
Block a user