示例 1:
输入: nums = [1,1,2,3,3,4,4,8,8]
输出: 2
示例 2:
输入: nums = [3,3,7,7,10,11,11]
输出: 10
package BinarySearch;
public class p540_SingleElementInSortedArray {
public static void main(String[] args) {
int[] nums = {1, 1, 2, 3, 3, 4, 4, 8, 8};
int res = singleNonDuplicate(nums);
System.out.println("res = " + res);
}
public static int singleNonDuplicate(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (mid % 2 == 1) {
mid--;
}
if (nums[mid] == nums[mid + 1]) {
left = mid + 2;
} else {
right = mid;
}
}
return nums[left];
}
}
#include
int singleNonDuplicate(int* nums, int numsSize)
{
int left = 0;
int right = numsSize - 1;
while (left < right)
{
int mid = left + (right - left) / 2;
if (mid % 2 == 1)
{
mid--;
}
if (nums[mid] == nums[mid + 1])
{
left = mid + 2;
}
else
{
right = mid;
}
}
return nums[left];
}
/*主函数省略*/
Java语言版
C语言版