log N binary search in Java


  • 0
    A
    public class Solution {
        public int singleNonDuplicate(int[] nums) {
            int i = 0; int j = nums.length - 1;
            int mid = -3;
      
            while(i < j){
                mid = i + (j - i)/2;
                if (mid == 0) return nums[mid];
                
                if ((mid % 2 == 1) && (nums[mid - 1] == nums[mid])) i = mid + 1;
                else if ((mid % 2 == 1) && (nums[mid + 1] == nums[mid])) j = mid - 1;
                else if ((mid % 2 == 0) && (nums[mid + 1] == nums[mid])) i = mid + 1;
                else if ((mid % 2 == 0) && (nums[mid - 1] == nums[mid])) j = mid - 1;
                else return nums[mid];
            
            }
            return nums[j];
        }
    }
    
    

Log in to reply
 

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