leetcode 540. Single Element in a Sorted Array

257 篇文章 17 订阅

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都是奇数。这就是上述解法的思想。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值