Easy Understanding code in Java


  • 2
    R

    Easy understanding solution using two pointers

    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> ret = new ArrayList<String>();
            if (nums == null || nums.length == 0) {
                return ret;
            }
            
            int prev = nums[0];
            int next = nums[0];
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] == nums[i - 1] + 1) {
                    next = nums[i];
                }
                else {
                    if (prev == next) {
                        ret.add("" + prev);
                    }
                    else {
                        ret.add("" + prev + "->" + next);
                    }
                    prev = nums[i];
                    next = nums[i];
                }
            }
            
            if (prev == next) {
                ret.add("" + prev);
            }
            else {
                ret.add("" + prev + "->" + next);
            }
            return ret;
        }
    }
    

Log in to reply
 

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