My java easy understanding solution


  • 2
    Y
    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList<String>();
        if(nums.length == 0) return result;
        int start = nums[0];
        int end = nums[0];
        for(int i = 1; i < nums.length; i++){
            if(nums[i] != nums[i - 1] + 1){
                if(start == end) result.add(String.valueOf(start));
                else result.add(String.valueOf(start) + "->" + String.valueOf(end));
                start = nums[i];
                end = nums[i];
            }else{
                end = nums[i];
            }
        }
        if(start == end) result.add(String.valueOf(start));
        else result.add(String.valueOf(start) + "->" + String.valueOf(end));
        return result;
    }

  • 0
    U
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> results = new ArrayList<String>();
            if (nums.length == 0) return results;
        
            int beginVal = nums[0];
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] + 0L - nums[i-1] > 1) {
                    results.add(constructRange(beginVal, nums[i-1]));
                    beginVal = nums[i];
                }
            }
        
            results.add(constructRange(beginVal, nums[nums.length-1]));
            return results;
        }
        
        private String constructRange(int beginVal, int endVal) {
            if (beginVal == endVal) {
                return beginVal + "";
            }
            return beginVal + "->" + endVal;
        }
    }

  • 0
    A

    what's with the 0L thing ?


  • 0
    U

    it casts integer to long


  • 0
    A

    I know that it got casted to Long, but I didn't get: why do you convert it to a long when the differene (1) could be handled by an int ?


  • 0
    U

    what if num[i] is 'INTEGER.MAX_VALUE' and num[i-1] is 'INTEGER.MIN_VALUE', would that be overflow situation?


  • 0
    A

    got it, so you could have done it the other way around, like:
    if(num[i]!=num[i-1]+1), without converting it to Long, right ?


  • 0
    U

    You can try with the test set. I believe it would still be overflow.


Log in to reply
 

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