package leetcode;

/**
 * https://leetcode.com/problems/single-element-in-a-sorted-array/
 */
public class Problem540 {
    public int singleNonDuplicate(int[] nums) {
        int i = 0;
        int j = nums.length - 1;
        while (i < j) {
            int tmpi = i;
            int tmpj = j;
            int mid = (i + j) / 2;
            if (mid + 1 < nums.length) {
                if (mid - 1 >= 0) {
                    if (nums[mid] == nums[mid - 1]) {
                        if ((mid - 1 - i) % 2 != 0) {
                            j = mid;
                        } else {
                            i = mid;
                        }
                    }
                }
                if (nums[mid] == nums[mid + 1]) {
                    if ((j - mid + 1) % 2 != 0) {
                        i = mid;
                    } else {
                        j = mid;
                    }
                }
            }
            if (tmpi == i && tmpj == j) {
                return nums[mid];
            }
        }
        return nums[i];
    }

    public static void main(String[] args) {
        Problem540 prob = new Problem540();
//        System.out.println(prob.singleNonDuplicate(new int[]{1, 1, 2, 3, 3, 4, 4, 8, 8})); // 2
//        System.out.println(prob.singleNonDuplicate(new int[]{3, 3, 7, 7, 10, 11, 11})); // 10
        System.out.println(prob.singleNonDuplicate(new int[]{1, 3, 3, 7, 7, 11, 11})); // 1
        System.out.println(prob.singleNonDuplicate(new int[]{1, 1, 3, 3, 7, 7, 11})); // 11
    }
}

@@ -495,12 +495,8 @@
  - 1
- - i
 ) %25 
@@ -532,32 +532,36 @@
          j = mid
+ - 1
 ;%0A              
@@ -606,32 +606,36 @@
          i = mid
+ + 1
 ;%0A              
@@ -761,17 +761,31 @@
    if ((
-j
+nums.length - 1
  - mid +
@@ -827,24 +827,28 @@
      i = mid
+ + 1
 ;%0A          
@@ -897,16 +897,20 @@
  j = mid
+ - 1
 ;%0A      
@@ -1090,481 +1090,7 @@
    %7D
-%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem540 prob = new Problem540();%0A//        System.out.println(prob.singleNonDuplicate(new int%5B%5D%7B1, 1, 2, 3, 3, 4, 4, 8, 8%7D)); // 2%0A//        System.out.println(prob.singleNonDuplicate(new int%5B%5D%7B3, 3, 7, 7, 10, 11, 11%7D)); // 10%0A        System.out.println(prob.singleNonDuplicate(new int%5B%5D%7B1, 3, 3, 7, 7, 11, 11%7D)); // 1%0A        System.out.println(prob.singleNonDuplicate(new int%5B%5D%7B1, 1, 3, 3, 7, 7, 11%7D)); // 11%0A    %7D
 %0A%7D%0A

Solve problem 540