Vary simple JAVA solution w/o extra memory


  • 0
    Y
    public class Solution {
    public int singleNumber(int[] A) {
        
        if (A.length==0) return -1;
        if (A.length==1) return A[0];
        if (A.length==2 && A[0]==A[1]) return -1;
        if (A.length==2 && A[0]!=A[1]) return A[0];
        
        Arrays.sort(A);
        int s=A[0];
        if (A[1]!=A[0]) return A[0];
        
        
        for (int i=2; i<A.length; i++){
            
            if (A[i] ==s){
                
                continue;
            }
            
            s=A[i];
            
            if (i+1==A.length || A[i+1] !=s){
                return s;
            }
        }
        
        return -1;
         
    }
    

    }


  • 0
    F

    I think a linear runtime complexity is required.


  • 0
    W

    The method Array.sort() uses merge sort,which costs O(n) in space.So I don't think java is effective in Algorithms.


Log in to reply
 

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