A simple solution in Java, 1 ms run time.


  • 0
    S

    Compare the number with numbers on left and right. If the number is different from the one on the left and right then that is the required number. For example, consider the sequence 1, 1, 2, 3, 3. Here the unique number is 2 and the two numbers on either side are unique.

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

Log in to reply
 

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