Problem Solving/LeetCode
2023.02.21 Today's Challenge
fabichoi
2023. 2. 21. 23:45
https://leetcode.com/problems/single-element-in-a-sorted-array/
Single Element in a Sorted Array - LeetCode
Can you solve this real interview question? Single Element in a Sorted Array - You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element
leetcode.com
어제에 이은 바이너리 서치 문제
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
l, r = 0, len(nums) // 2
ans = -1
while l <= r:
mid = (l+r) // 2
idx = mid * 2
if idx + 1 >= len(nums) or nums[idx] != nums[idx+1]:
r = mid-1
ans = nums[idx]
else:
l = mid + 1
return ans
반응형