标签:HERE 观察 mic lse ever 二分法 hub int element
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
标签:HERE 观察 mic lse ever 二分法 hub int element
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12880270.html