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.java
Example 1:app
Input: [1,1,2,3,3,4,4,8,8] Output: 2
Example 2:this
Input: [3,3,7,7,10,11,11] Output: 10
Note: Your solution should run in O(log n) time and O(1) space.spa
題目地址code
二分查找,包含一個數的一邊個數必定是奇數個。element
class Solution { public int singleNonDuplicate(int[] nums) { return binarySearch(nums, 0, nums.length-1); } private int binarySearch(int[] nums, int left, int right){ if(left==right){ return nums[left]; } int mid = (left+right)/2; if(nums[mid-1]==nums[mid]){ if((right-mid)%2==1){ return binarySearch(nums, mid+1, right); }else{ return binarySearch(nums, left, mid-2); } }else if(nums[mid+1]==nums[mid]){ if((mid-left)%2==1){ return binarySearch(nums, left, mid-1); }else{ return binarySearch(nums, mid+2, right); } }else{ return nums[mid]; } } }