Dummy Java O(N) solution


  • 0
    O
    public class Solution {
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            int len = nums.length;
            List<String> res = new ArrayList<String>();
            StringBuilder sb = new StringBuilder();
            if(len == 0){
                if(lower == upper) sb.append(lower);
                else {
                    sb.append(lower);
                    sb.append("->");
                    sb.append(upper);
                }
                res.add(sb.toString());
                return res;
            }
            if(lower < nums[0]){
                if(lower == nums[0]-1) sb.append(lower);
                else{
                    sb.append(lower);
                    sb.append("->");
                    sb.append(nums[0]-1);
                }
                res.add(sb.toString());
                sb = new StringBuilder();
            }
            helper(nums,res);
            if(upper > nums[len-1]){
                if(upper == nums[len-1]+1) sb.append(upper);
                else{
                    sb.append(nums[len-1]+1);
                    sb.append("->");
                    sb.append(upper);
                }
                res.add(sb.toString());
            }
            return res;
        }
        
        public void helper(int[] nums, List<String> list){
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < nums.length-1; i++){
                if((long)nums[i+1] - (long)nums[i] <= 1) continue;
                if((long)nums[i+1] - (long)nums[i] >= 2){
                    if(nums[i+1] - nums[i] == 2) sb.append(nums[i+1]-1);
                    else{
                        sb.append(nums[i]+1);
                        sb.append("->");
                        sb.append(nums[i+1]-1);
                    }
                    list.add(sb.toString());
                    sb = new StringBuilder();
                }
            }
        }
    }
    

Log in to reply
 

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