mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-24 00:57:05 +08:00
add python算法模版
This commit is contained in:
@ -803,6 +803,46 @@ Java:
|
|||||||
|
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
## 二分查找法
|
||||||
|
```python
|
||||||
|
def binarysearch(nums, target):
|
||||||
|
low = 0
|
||||||
|
high = len(nums) - 1
|
||||||
|
while (low <= high):
|
||||||
|
mid = (high + low)//2
|
||||||
|
|
||||||
|
if (nums[mid] < target):
|
||||||
|
low = mid + 1
|
||||||
|
|
||||||
|
if (nums[mid] > target):
|
||||||
|
high = mid - 1
|
||||||
|
|
||||||
|
if (nums[mid] == target):
|
||||||
|
return mid
|
||||||
|
|
||||||
|
return -1
|
||||||
|
```
|
||||||
|
|
||||||
|
## KMP
|
||||||
|
|
||||||
|
```python
|
||||||
|
def kmp(self, a, s):
|
||||||
|
# a: length of the array
|
||||||
|
# s: string
|
||||||
|
|
||||||
|
next = [0]*a
|
||||||
|
j = 0
|
||||||
|
next[0] = 0
|
||||||
|
|
||||||
|
for i in range(1, len(s)):
|
||||||
|
while j > 0 and s[j] != s[i]:
|
||||||
|
j = next[j - 1]
|
||||||
|
|
||||||
|
if s[j] == s[i]:
|
||||||
|
j += 1
|
||||||
|
next[i] = j
|
||||||
|
return next
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
Reference in New Issue
Block a user