540. Single Element in a Sorted Array
Posted wentiliangkaihua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了540. 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
Example 2:
Input: [3,3,7,7,10,11,11] Output: 10
class Solution { public int singleNonDuplicate(int[] nums) { int res = 0; for(int i: nums) res = res^i; return res; } }
这题不涉及O(logN)还是很愉快的,一波异或带走,和single number一样
假如要求O(logN),说明要二分法
class Solution { public int singleNonDuplicate(int[] nums) { int left = 0, right = nums.length - 1; while(left < right){ int mid = right + (left-right)/2; if(mid % 2 == 1) mid--; if(nums[mid] == nums[mid + 1]) left += 2; else right = mid; } return nums[left]; } }
观察一下,mid和mid+1如果相等就说明在右边,否则一定在左边
比如1,1,2,2,3,4,4,先设定mid一定是偶数,才能比较mid和mid+1,因为left<right,所以mid+1一定存在。如果mid是奇数就要mid--。
带个大佬的图比较清楚
以上是关于540. Single Element in a Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章
540. Single Element in a Sorted Array
540. Single Element in a Sorted Array
540. Single Element in a Sorted Array(LeetCode)
[LeetCode] 540. Single Element in a Sorted Array