Java AC solution handling edge cases.


  • 1

    Go 1 by 1 num see anything missing, if missing, add to the list (depends on the missing size, add either a num or a num1->num2).

    public class Solution {
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            List<String> list = new ArrayList<String>();
            int preMiss = lower;
            for (int num : nums) {
                if (num == Integer.MAX_VALUE) {
                    if (upper == num)
                        --upper;
                    break;
                }
                preMiss = getNext(preMiss, num, list);
            }
            if (preMiss == upper)
                list.add(preMiss + "");
            else if (preMiss < upper)
                list.add(preMiss + "->" + upper);
            return list;
        }
    
        private static int getNext(int miss, int num, List<String> list) {
            if (miss < num) {
                if (miss == num - 1)
                    list.add(miss + "");
                else
                    list.add(miss + "->" + (num - 1));
            }
            return num + 1;
        }
    }
    

  • 0

    This solution can pass the OJ..
    Hope that they don't change the test cases too frequently..or maybe they can disclose some test cases.
    A lot of test cases have no meaning and sometimes it's not worth to debug to avoid each one wrong answer.


  • 0

    It works exactly as the OJ works. I think there's an assumption that the array must be inside the interval.


Log in to reply
 

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