Easy Java solution with explanation


  • 0
    M

    This problem must probably belong to EASY category
    The idea is that, since the array is a sorted array, every element that appears twice appears consecutively in the array. We take two variables to point to the consecutive indices. when the values pointed by the indices are not same, then the value at the first index is the number that appears only once. if the values are equal we increment both indices by 2.
    Here's my accepted solution

    class Solution {
        public int singleNonDuplicate(int[] nums) {
            int index=0;
            for(int i=0,j=1;i<nums.length && j<nums.length;){
                if(nums[i]==nums[j]){
                    i = i+2;
                    j = j+2;
                    index = i;
                }
                else{
                    return nums[i];
                }
            }
            return nums[index];
        }
    }
    

Log in to reply
 

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