Home LeetCode. 540. Single Element in a Sorted Array
Post
Cancel

LeetCode. 540. Single Element in a Sorted Array

image

[Link] https://leetcode.com/problems/single-element-in-a-sorted-array/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public int singleNonDuplicate(int[] nums) {
        int start = 0, end = nums.length - 1, mid;
        while(start <= end) {
            mid = (start + end) / 2;
            boolean pre = false, post = false;
            if(mid > 0 && nums[mid - 1] == nums[mid]) {
                if((mid & 1) == 0) pre = true;
                else post = true;
            }
            else if(mid < nums.length - 1 && nums[mid + 1] == nums[mid]) {
                if((mid & 1) == 0) post = true;
                else pre = true;
            }
            if(pre) end = mid - 1;
            else if(post) start = mid + 1;
            else return nums[mid];
        }
        return 0;
    }
}
This post is licensed under CC BY 4.0 by the author.