Java 10 line easy to understand solution


  • 1
    V
    public class Solution {
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            List<String> list = new ArrayList<String>();
            for(int n : nums){
                int justBelow = n - 1;
                if(lower == justBelow) list.add(lower+"");
                else if(lower < justBelow) list.add(lower + "->" + justBelow);
                lower = n+1;
            }
            if(lower == upper) list.add(lower+"");
            else if(lower < upper) list.add(lower + "->" + upper);
            return list;
        }
    }

  • 0
    D

    @vimukthi well, I think you should consider if some elements are bigger than upper.


  • 0
    S

    Wrong Answer.
    e.g
    arr = {0,1,3,50,75}; int low = -2;int up = 55;


  • 0
    S
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        List<String> list = new ArrayList<String>();
        for(int n : nums){
            int justBelow = n - 1;
            if(justBelow>upper) break;
            if(lower == justBelow) list.add(lower+"");
            else if(lower < justBelow) list.add(lower + "->" + justBelow);
            lower = n+1;
        }
        if(lower == upper) list.add(lower+"");
        else if(lower < upper) list.add(lower + "->" + upper);
        return list;
    }

Log in to reply
 

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