题目:
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
Note: Your solution should run in O(log n) time and O(1) space.
题目描述:
给定一个数组,数组中只有一个数出现一次,其他的都出现两次,找出这个出现一次的数。
解题思路:
容易想到利用二分查找,保证每次区间的两段都是偶数,以便区间内数的个数为奇数,根据nums[mid]是否和nums[mid+1]相等,确定下一次的区间范围。具体代码及解题思路如下:
package Leetcode_Github; public class BinarySearch_SingleNonDuplicate_540_1113 { public int SingleNonDuplicate(int[] nums){ int l = 0;//初始化l为数组第一个元素 int h = nums.length - 1;//初始化h为数组末尾元素 while (l < h) { int mid = l + (h - l) / 2; //如果mid是奇数,将mid减1,保证l、m、h均为偶数,区间有奇数个数 if (mid % 2 == 1) { mid--; } //如果相等,说明出现一次的数在后半段 if (nums[mid] == nums[mid + 1]) { l = mid + 2; } else h = mid; } return nums[l]; } }