2ms Java Solution -Easy to understand


  • 0
    G

    ...

    .

    public class Solution {
    public int singleNonDuplicate(int[] array) {

    	int ret = -1;
    	if(array==null) {
    		return -1;
    	}
    	
    	if(array.length==1) {
    		return array[0];
    	}
    	
    	else {
    		for(int k=0;k<array.length;k++) {
    			// if it is 1st element check next one
    			if(k==0 ) {
    				if(array[k]!=array[k+1]) {
    					ret= array[k];
    				}										
    			}
    			else if(k==array.length-1) {
    				if(array[k]!=array[k-1]) {
    					ret= array[k];
    				}										
    				
    			}
    			else {
    				// if element not equal to neighbors then
    				if(array[k]!=array[k-1] && array[k]!=array[k+1]) {
    					ret = array[k];
    				}
    			}				
    		}
    	}
    			
    	return ret;
          
    }
    

    }
    ...


Log in to reply
 

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