1 ms Java Solution, Binary Search, Easy to Understand


  • 0
    public class Solution {
        public int singleNonDuplicate(int[] nums) {
            int low = 0;
            int high = nums.length - 1;
            return getNumber(low, high, nums);
        }
        
        private int getNumber(int low, int high, int[] nums) {
            int mid = 0;
            while(low < high) {
                mid = low + (high-low)/2;
                if(mid%2 == 0) {
                    if(nums[mid+1] != nums[mid]){
                        high = mid - 1;
                    }
                    else {
                        low = mid + 1;
                    }
                }
                else {
                    if(nums[mid-1] == nums[mid]) {
                        low = mid + 1;
                    }
                    else {
                        high = mid - 1;
                    }
                }
            }
            return nums[low];
        }   
    }
    

Log in to reply
 

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