-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path457.classical-binary-search.py
76 lines (65 loc) · 1.52 KB
/
457.classical-binary-search.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Tag: Binary Search
# Time: O(logN)
# Space: O(1)
# Ref: -
# Note: -
# 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):
# write your code here
n = len(nums)
start = 0
end = n
while start < end:
mid = start + (end - start) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
start = mid + 1
else:
end = mid
return -1
class Solution:
"""
@param nums: An integer array sorted in ascending order
@param target: An integer
@return: An integer
"""
def findPosition(self, nums, target):
# write your code here
n = len(nums)
if n == 0:
return -1
left = 0
right = n - 1
while left < right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1
else:
right = mid
return -1 if nums[left] != target else left