LeetCode知识点总结 - 540
LeetCode 540. Single Element in a Sorted Array
| 考点 | 难度 |
|---|---|
| Array | Medium |
题目
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.
思路
Before the single element x pairs start at even indices. At/after the single element x this pattern breaks
答案
classSolution{publicintsingleNonDuplicate(int[]nums){intleft=0,right=nums.length-1;while(left<right){intmid=(left+right)/2;if((mid%2==0&&nums[mid]==nums[mid+1])||(mid%2==1&&nums[mid]==nums[mid-1]))left=mid+1;elseright=mid;}returnnums[left];}}