540. Single Element in a Sorted Array
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 that appears only once.
Your solution must run in O(log n) time and O(1) space.
Example 1:
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: nums = [3,3,7,7,10,11,11]
Output: 10
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 105
思路:
用二分搜索做,看第二个相同数字的下标是奇数还是偶数就可以判断
代码:
func singleNonDuplicate(nums []int) int {
n := len(nums)
if n == 1{
return nums[0]
}
l,r := 0,n-1
for l<=r{
mid := (l+r)/2
if mid<n-1{
if nums[mid] == nums[mid+1]{
mid++
}
}
if mid % 2 == 0{
r = mid-1
}else{
l = mid+1
}
}
return nums[l]
}
代码效率:
执行用时:20 ms, 在所有 Go 提交中击败了73.93%的用户
内存消耗:7.8 MB, 在所有 Go 提交中击败了86.32%的用户
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!