Leetcode - Single Element in a Sorted Array
https://leetcode.com/problems/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. Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8] Output: 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | func singleNonDuplicate(nums [] int ) int { if len(nums) == 1 { return nums[0] } left := 0 right := len(nums)-1 var mid int for left < right { mid = (left+right)/2 if mid%2 == 1 { mid-- } if nums[mid] != nums[mid+1] { right = mid } else { left = mid + 2 } } return nums[left] } |