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.java
Example 1:数组
Input: [1,1,2,3,3,4,4,8,8]
Output: 2app
Example 2:this
Input: [3,3,7,7,10,11,11]
Output: 10spa
Note:Your solution should run in O(log n) time and O(1) space.code
现有一个有序的递增的整数数组,其中除了一个数字以外,每一个数字都出现了两次。要求用O(log n)的时间复杂度和O(1)的空间复杂度找出只出现一次的数字。递归
已知 a ^ a = 0,利用这个结论,能够对全部的数字执行异或操做,最终异或的结果就是只出现一次的数字。element
public int singleNonDuplicate(int[] nums) { int result = 0; for (int num : nums) { result ^= num; } return result; }
O(log n)的时间复杂度一般都和二分法有关,而这里的二分法的思考点在于如何寻找中间位置,以及用什么判断逻辑来决定是继续递归处理左子数字仍是右子数组。io
一旦找到合适的中间位置,咱们就应该能够判断出来单个数字到底是出如今左子数字仍是右子数字。那么咱们的目标就应该是找到中间的重复数对的第一个数字。假如咱们默认左子数组中不存在单个数字,则说明中间数对应该是位于一个偶数下标上,以下:class
0 1 2 3 4 1 1 3 3 5 ^
可是假如单个数字在左子数组,则咱们找到的中间位置偶数下标上的数字就不是重复数对的第一个下标
0 1 2 3 4 1 2 2 3 3 ^
所以找到中间位置的偶数下标上的值,而且和后面的数字进行比较,就知道单个数字究竟在左边仍是在右边。
public int singleNonDuplicate2(int[] nums) { int start = 0, end = nums.length - 1; while (start < end) { int mid = (start + end) / 2; //假设左半边子数组均为重复数字,则默认的中间数对的第一个数字的下标必定为偶数 //找到中间数对第一个数字的下标 if (mid % 2 == 0) {mid -= 1;} //中间数对为重复数字,说明单个数字在右半边 if (nums[mid] == nums[mid + 1]) { start = mid + 2; } else { end = mid - 1; } } return start; }