Keeping it simple!


  • 0
    P

    Its a Sorted array and 1 solution always exists, then lets keep it simple and just compare prev with next!
    best case solution falls at the start of the array, worst case O(n) when the solution is at the end.

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

Log in to reply
 

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