mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-30 04:36:08 -04:00
Update README.md
This commit is contained in:
parent
ff73b28ae7
commit
f2091f10d2
@ -72,6 +72,29 @@ def binary_search_recursive(array, item, higher=None, lower=0):
|
|||||||
|
|
||||||
<br>
|
<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
|
### in a matrix
|
||||||
@ -127,10 +150,8 @@ def sqrt(x) -> int:
|
|||||||
|
|
||||||
if num > x:
|
if num > x:
|
||||||
right = mid - 1
|
right = mid - 1
|
||||||
|
|
||||||
elif num < x:
|
elif num < x:
|
||||||
left = mid + 1
|
left = mid + 1
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return mid
|
return mid
|
||||||
|
|
||||||
@ -190,3 +211,63 @@ def peak_element(nums):
|
|||||||
|
|
||||||
return left
|
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