- 540. Single Element in a Sorted
- 540. Single Element in a Sorted
- 540. Single Element in a Sorted
- 540. Single Element in a Sorted
- 540. Single Element in a Sorted
- 540. Single Element in a Sorted
- 540. Single Element in a Sorted
- 刷题(10)leetcode 540 --binary sear
- 【Leetcode】540. Single Element in
- 540.Single Element in a Sorted A
Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: [3,3,7,7,10,11,11]
Output: 10
这题是用binary search做。
这题比较难的地方是在于怎么处理细节
你取的那个mid = l + (r - l) / 2 可能是奇数也可能是偶数
是奇数怎么办,是偶数怎么办?
下面是是一个别外学来的很巧妙的处理方式
public int singleNonDuplicate(int[] nums) {
int l = 0, r = nums.length - 1;
while (l < r) {
int m = l + (r - l) / 2;
if (m % 2 == 1) m--; //先看是不是偶数,不是的话m--变成偶数
if (nums[m + 1] == nums[m]) l = m + 2; //和它下一个比 不用担心出界的问题
else r = m;
}
return nums[l];
}
网友评论