Java Binary Search EZ understanding


  • 0
    F
    public class Solution {
        public int singleNonDuplicate(int[] nums) {
            if(nums == null || nums.length == 0) {
                return -1;
            }
            int start = 0, end = nums.length - 1;
            while(start + 1 < end) {
                int mid = start + (end - start) / 2;
                if(mid % 2 != 0) {
                    if(nums[mid] != nums[mid - 1]) {
                        end = mid;
                    } else {
                        start = mid;
                    }
                } else {
                    if(nums[mid] == nums[mid + 1]) {
                        start = mid;
                    } else {
                        end = mid;
                    }
                }
            }
            if(start % 2 == 0 && nums[start] != nums[start + 1]) {
                return nums[start];
            } else {
                return nums[end];
            }
            
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.