Self-expalainable Java solution. Readability is important.


  • 0
    D

    Here is my solution for everyone's reference!

    public class Solution {
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            List<String> result = new ArrayList();
            // add full range if the array is empty
            if (nums.length == 0) {
                addRange(result, lower, true, upper, true);
                return result;
            }
            
            int pre = lower;
            for (int i = 0; i < nums.length; i++) {
                int cur = nums[i];   
                // put lower at the beginning of the array
                if (i == 0) { 
                    addRange(result, pre, true, cur, false);    
                }
                addRange(result, pre, false, cur, false);
                pre = cur;
                // put upper at the end of the array 
                if (i == nums.length - 1) {
                    addRange(result, cur, false, upper, true);
                }
            }
            return result;
        }
        private void addRange(List<String> result, int left, boolean includeLeft, int right, boolean includeRight) {
            int diff = right - left;
            if (diff == 0 && includeLeft && includeRight) {
                result.add(left + "");
            } else if (diff == 1) {
                if (includeLeft && includeRight) {
                    result.add(left + "->" + right);
                } else if (includeLeft) {
                    result.add(left + "");
                } else if (includeRight) {
                    result.add(right + "");
                }
            } else if (diff >= 2) {
                if (includeLeft && includeRight) {
                    result.add(left + "->" + right);
                } else if (includeLeft) {
                    result.add(left + "->" +(right - 1));
                } else if (includeRight) {
                    result.add((left + 1) + "->" + right);
                } else {
                    if (diff == 2) {
                        result.add((left + 1) + "");
                    } else {
                        result.add((left + 1) + "->" + (right - 1));
                    }
                }
            }
        }
    }
    

Log in to reply
 

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