Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 100b296

Browse files
authored
Add files via upload
1 parent d1afc7f commit 100b296

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
def binary_search(array, target):
2+
left = 0
3+
right = len(array) - 1
4+
while left <= right:
5+
mid = (left + right) // 2
6+
if array[mid] == target:
7+
return mid
8+
if array[mid] < target:
9+
left = mid + 1
10+
else:
11+
right = mid - 1
12+
13+
14+
15+
##################################################################
16+
17+
18+
19+
def single_non_duplicate(nums):
20+
21+
# Initialize left and right pointers
22+
left = 0
23+
right = len(nums) - 1
24+
25+
while left != right:
26+
27+
# Calculate the midpoint of the array
28+
middle = left + (right - left) // 2
29+
30+
# If mid-point is odd, decrement to make it even
31+
if middle % 2 != 0:
32+
middle -= 1
33+
34+
# If middle and middle + 1 are the same, then single element after mid-point
35+
if nums[middle] == nums[middle + 1]:
36+
left = middle + 2
37+
38+
# Otherwise search for single element before mid-point
39+
else:
40+
right = middle
41+
42+
# Return single element value
43+
return nums[left]
44+
45+
46+
47+
# Time Complexity = O(logn)
48+
# Space Complexity = O(1)
49+
50+
51+
52+
##################################################################
53+
54+
55+
56+
# Driver code
57+
def main():
58+
59+
nums = [[1, 2, 2, 3, 3, 4, 4], [1, 1, 2, 2, 3, 4, 4, 5, 5], [1, 1, 2, 3, 3], [1, 1, 2], [0, 2, 2, 3, 3, 4, 4, 5, 5]]
60+
61+
for i in range(len(nums)):
62+
print(str(i + 1) + ".\tThe Array = ", nums[i] , sep = "")
63+
print("\tSingle Element Found: ", single_non_duplicate(nums[i]), sep = "")
64+
print("-" * 100)
65+
66+
if __name__ == '__main__':
67+
main()
68+
69+
70+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /