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.
简单题。package leetcode;
public class Single_Element_in_a_Sorted_Array_540 {
public int singleNonDuplicate(int[] nums) {
int n=nums.length;
for(int i=0;i*2+1<n;i++){
int thisNumber=nums[i*2];
int nextNumber=nums[i*2+1];
if(thisNumber!=nextNumber){
return thisNumber;
}
}
return nums[n-1];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Single_Element_in_a_Sorted_Array_540 s=new Single_Element_in_a_Sorted_Array_540();
int[] nums=new int[]{3,3,7,7,10,11,11};
System.out.println(s.singleNonDuplicate(nums));
}
}
大神想到用二分查找。
这里的lo和hi并不是指真实的index,而是pair index,后续要*2或*2+1才能得到真实的index。
public class Solution {
public int singleNonDuplicate(int[] nums) {
// binary search
int n=nums.length, lo=0, hi=n/2;
while (lo < hi) {
int m = (lo + hi) / 2;
if (nums[2*m]!=nums[2*m+1]) hi = m;
else lo = m+1;
}
return nums[2*lo];
}
}i 0 1 2 3 4 5 6 7 8
nums[] 1 1 2 2 3 4 4 5 5
可以看到,在出现单独的数之前,pair的第一个数的index都是偶数,而在出现单独的数之后,pair的第一个数的index都是奇数。这就是上述解法的思想。

本文介绍了一种在已排序的整数数组中找到唯一出现一次的元素的方法,并提供了一个简单的线性扫描解决方案以及一个更高效的二分查找算法实现。
937

被折叠的 条评论
为什么被折叠?



