-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindexEqualsValue.py
48 lines (37 loc) · 1.47 KB
/
indexEqualsValue.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# def indexEqualsValue(array):
# indexArray = [i for i in range(len(array))]
# for i in range(len(array)):
# if array[i] == indexArray[i]:
# return i
# return -1
# def indexEqualsValue(array):
# return indexEqualsValueHelper(array, 0, len(array)-1)
# def indexEqualsValueHelper(array, leftIdx, rightIdx):
# while leftIdx <= rightIdx:
# middleIdx = leftIdx + (rightIdx-leftIdx)//2
# middleValue = array[middleIdx]
# if middleValue == middleIdx and middleIdx==0 :
# return middleIdx
# elif middleValue < middleIdx:
# leftIdx = middleIdx+1
# elif middleValue == middleIdx and array[middleIdx-1]<middleIdx-1:
# return middleIdx
# else:
# rightIdx = middleIdx-1
# return -1
def indexEqualsValue(array):
return indexEqualsValueHelper(array, 0, len(array)-1)
def indexEqualsValueHelper(array, leftIdx, rightIdx):
if leftIdx > rightIdx:
return -1
middleIdx = leftIdx + (rightIdx-leftIdx)//2
middleValue = array[middleIdx]
if middleValue < middleIdx:
return indexEqualsValueHelper(array, middleIdx+1, rightIdx)
elif middleValue == middleIdx and middleIdx == 0:
return middleIdx
elif middleValue == middleIdx and array[middleIdx-1] < middleIdx-1:
return middleIdx
else:
return indexEqualsValueHelper(array, leftIdx, middleIdx-1)
print(indexEqualsValue([-2, 0, 2, 4, 6, 8, 10]))