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

540. Single Element in a Sorted Array

时间:2020-05-13 10:07:23      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:HERE   观察   mic   lse   ever   二分法   hub   int   element   

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.

 

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
class Solution {
    public int singleNonDuplicate(int[] nums) {
        int res = 0;
        for(int i: nums) res = res^i;
        return res;
    }
}

这题不涉及O(logN)还是很愉快的,一波异或带走,和single number一样

假如要求O(logN),说明要二分法

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

观察一下,mid和mid+1如果相等就说明在右边,否则一定在左边

比如1,1,2,2,3,4,4,先设定mid一定是偶数,才能比较mid和mid+1,因为left<right,所以mid+1一定存在。如果mid是奇数就要mid--。

技术图片

 

 https://github.com/Cee/Leetcode/blob/master/540%20-%20Single%20Element%20in%20a%20Sorted%20Array.java

带个大佬的图比较清楚

540. Single Element in a Sorted Array

标签:HERE   观察   mic   lse   ever   二分法   hub   int   element   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12880270.html

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