Leetcode - Single Element in a Sorted Array
violet
posted @ Mar 24, 2020 11:07:54 AM
in 算法
with tags
Algorithm Golang BinarySearch array
, 218 阅读
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
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] }