Another pass solution - java verison


  • 0
    R

    key points

    1. make sure handle edge cases.
    2. centralize ranges into a function
    public class Solution {
        public List<String> findMissingRanges(int[] A, int lower, int upper) {
            
            List<String> ranges = new ArrayList<String>();
            
            if (lower > upper) return ranges;
            
            if (A == null || A.length == 0) {
                updateRanges(lower-1, upper+1, ranges);
                return ranges;
            }
            
            int start = 0;
            int end = A.length-1;
            while (start < A.length && A[start] < lower) {
                start++;
            }
            while (end >= 0 && A[end] > upper) {
                end--;
            }
            
            if (start == A.length || end == -1) {
                updateRanges(lower-1, upper+1, ranges);
            } else {
                updateRanges (lower-1, A[start], ranges);
                for (int i = start; i<end; i++) {
                    updateRanges(A[i], A[i+1], ranges);
                }
                updateRanges(A[end], upper+1, ranges);
            }
            return ranges;
        }
        
        private void updateRanges(int start, int end, List<String> ranges) {
            StringBuilder sb = new StringBuilder();
            if (end - start > 1) {
                sb.append(start+1);
                if (end - start > 2) {
                    sb.append("->");
                    sb.append(end-1);
                }
                ranges.add(sb.toString());
            }
        }
    }

Log in to reply
 

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