码迷,mamicode.com
首页 > 其他好文 > 详细

【每日一题】- Leetcode 540. Single Element in a Sorted Array

时间:2020-05-15 00:27:32      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:dup   log   ica   time   length   note   esc   which   rip   

Description: You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.

Note:

  • Your solution should run in O(log n) time and O(1) space.

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


 

Intuition:

1. O(logN), binary search

2. The subarray containing the single element must be odd-lengthed, and the subarray containing it must be even-lengthed.

3. Every time examine the middle element and its neighbor, taking out this pair and moving the lo/hi pointer according to the odd/even length of the subarray.

4. Solution:

class Solution {
    public int singleNonDuplicate(int[] nums) {
        int lo = 0, hi = nums.length - 1;
        
        while (lo < hi) {
            int mid = lo + (hi - lo)/2;
            if (nums[mid] == nums[mid + 1]) {
                if ((hi -(mid + 2) + 1)%2 == 1) lo = mid + 2;
                else hi = mid - 1;
            } else if (nums[mid] == nums[mid - 1]) {
                if ((mid - 2 - lo + 1)%2 == 1) hi = mid - 2;
                else lo = mid + 1;
            } else return nums[mid];
        }
        return nums[lo];
    }
}

Reference: https://leetcode.com/problems/single-element-in-a-sorted-array/

 

【每日一题】- Leetcode 540. Single Element in a Sorted Array

标签:dup   log   ica   time   length   note   esc   which   rip   

原文地址:https://www.cnblogs.com/yy0506/p/12892193.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!