-
Notifications
You must be signed in to change notification settings - Fork 0
/
day1
30 lines (29 loc) · 792 Bytes
/
day1
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
'''
01.Classical Binary Search
Description
Find any position of a target number in a sorted array. Return -1 if target does not exist.
Example 1:
Input: nums = [1,2,2,4,5,5], target = 2
Output: 1 or 2
Example 2:
Input: nums = [1,2,2,4,5,5], target = 6
Output: -1
# '''
class Solution:
"""
@param nums: An integer array sorted in ascending order
@param target: An integer
@return: An integer
"""
def findPosition(self, nums, target):
left = 0
right = len(nums)-1
while left<=right:
mid = left + (right-left)//2
if target > nums[mid]:
left = mid+1
elif target < nums[mid]:
right = mid-1
elif target == nums[mid]:
return mid
return -1