Java solution -- pure labor work to check all corner cases -- no fun


  • 0
    L

    This is the worst interview question I would expect: purely labor work and no interesting ideas can be applied. Could sb. give a smarter solution that is simpler?

    public static List<String> findMissingRanges(int[] A, int lower, int upper) {
            
            
            List<String> rst = new ArrayList<String>();
            
            if(A.length==0){
                updateRst(rst, lower, upper);
                return rst;
            }
            
            // (, lower) ignore
            int i=0;
            while(i<A.length && A[i]<lower){ 
                i++;
            }
            
            if(i==A.length){
                return rst;
            }
            
            int pre = A[i];
            if(A[i]>lower){
                updateRst(rst, lower, A[i]-1);
                pre = A[i];
            }
            i++;
            
            // [lower, upper] inclusive.
            while(i<A.length && A[i]<=upper){
                if(A[i]!=pre+1){
                    updateRst(rst, pre+1, A[i]-1);
                }
                pre = A[i];
                i++;
            }
            if(i==A.length){
                updateRst(rst, pre+1, upper);
            }
            
            // (upper, ) ignore
            
            return rst;
        }
        
        public static void updateRst(List<String> rst, int a, int b){
        	
        	if(a>b) return;  // treatment for pre+1==upper
        	if (a==b){
                rst.add(String.valueOf(a));
            }else{
                rst.add(String.valueOf(a) + "->" + String.valueOf(b)); 
            }
        }

Log in to reply
 

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