Accepted JAVA solution--easy to understand


  • 76
    T
    List<String> list=new ArrayList();
    	if(nums.length==1){
    		list.add(nums[0]+"");
    		return list;
    	}
        for(int i=0;i<nums.length;i++){
        	int a=nums[i];
        	while(i+1<nums.length&&(nums[i+1]-nums[i])==1){
        		i++;
        	}
        	if(a!=nums[i]){
        		list.add(a+"->"+nums[i]);
        	}else{
        		list.add(a+"");
        	}
        }
        return list;

  • 4
    M

    good solution, but i think the first part checking length==1 is not necessary


  • 0
    T

    @magicalcan
    checking length==1 is required. otherwise:
    ==> nums[i+1]-nums[i])==1
    would give NULL POINTER EXCEPTION.


  • 3
    B

    @tajinder No, it's not necessary because && has a short-cut effect. If length == 1, i+1 < length is false and the condition checking will not check the second part.


  • -3
    D
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
                  List<String> ls = new ArrayList<String>();
                  if(nums==null || nums.length==0)
                  return ls;
                  
                 String start=nums[0]+"";
              String end=start; int k=0;
             for(int i=1;i<nums.length;i++){
                 if(nums[i]-nums[i-1]==1) {
                    end=nums[i]+"";
     
                     continue;
                 }
                 else{
                     
                     if(!start.equals(end))
                     ls.add(start+"->"+end);
                     else
                     ls.add(start);
                     
                     end=start=nums[i]+"";
                 }
             }
           
             if(!start.equals(end))
                     ls.add(start+"->"+end);
                     else
                     ls.add(start);
             return ls;
        }
    }

  • 1
    R

    +1
    length == 1 check is unnecessary.


  • 0
    H

    I prefer one loop, although yours is also O(n)


  • 0

    Thanks for sharing! Similar idea but I think mine is a little simpler. :) https://discuss.leetcode.com/topic/55491/very-easy-java-10-line-solution


  • 2
    F
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> ans = new ArrayList<String>();
            for(int i=0;i<nums.length;) {
                int start = i;
                while(i+1<nums.length&&nums[i+1]-nums[i]==1) {
                    i++;
                }
                if(nums[i]>nums[start]) {
                    ans.add(nums[start]+"->"+nums[i]);
                }else if(nums[i]==nums[start]) {
                    ans.add(""+nums[i]);
                }
                i++;
            }
            return ans;
        }
    }
    

  • 0
    B
    This post is deleted!

  • 0
    S

    Thanks for sharing.
    BTW, I've tried the corner case, which adds the condition that the nums array is null, and it was also accepted.
    I wonder why OJ accept your solution here.

    if(nums == null || nums.length ==1) {
    list.add(nums[0]+"");
    return list;
    }

    However, if I add the array nums <= 1, that will show error.
    "java.lang.ArrayIndexOutOfBoundsException: 0"

    I guess it might be the return value issue. Any idea about this, please?


  • 0
    T

    @magicalcan
    Yes, u r right! That's my coding habit! When special case happen, always deal with it first. When length was 1, the code after first return won't ex! I assume this will reduce the load of the memory stack, I am not sure my thought was right.


  • 0
    T

    @Taj.trojan when i = 1 while(i+1<nums.length) will never ex..


  • 0
    T

    @sgoogs The nums = null and the nums.lenght =0 is different. Here the OJ will accept because the input don't include null nums, input will include empty arrays.

    And, if you add nums <=1, when nums.length = 0 but not null! the nums[0] will give this error.


  • 0
    S

    @tanchiyuxx said in Accepted JAVA solution--easy to understand:

    @sgoogs The nums = null and the nums.lenght =0 is different. Here the OJ will accept because the input don't include null nums, input will include empty arrays.

    And, if you add nums <=1, when nums.length = 0 but not null! the nums[0] will give this error.

    Thanks! Do you mean that in this problem, we don't need to consider the null condition, please?


  • 1
    T

    @sgoogs No,no, always think the 'null' was good habit. For the problem, the input test case didn't include null. So you can pass! if you test in local, the null will give null exception in java


  • 0
    S

    @tanchiyuxx that's what I think. I will consider it anytime like you consider the 1 condition. LOL , even though 1 is not necessary here.
    Thanks! : )


  • 1

    Thanks for your sharing, and this is my c++ code with your method.

    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> res;
            for (int i = 0; i < nums.size(); ++i) {
                int num = nums[i];
                while (i + 1 < nums.size() && nums[i] == nums[i + 1] - 1)
                    ++i;
                if (nums[i] != num)
                    res.push_back(to_string(num) + "->" + to_string(nums[i]));
                else
                    res.push_back(to_string(nums[i]));
            }
            return res;
        }
    };
    

  • 0

    Similar solution with a single loop:

    public List<String> summaryRanges(int[] nums) {
      List<String> results = new ArrayList<>();
      for (int start = 0, end = 1; end <= nums.length; end++)
        if ((end == nums.length) || ((1 + nums[end - 1]) != nums[end])) {
          String suffix = (1 + start != end) ? "->" + nums[end - 1] : "";
          results.add(nums[start] + suffix);
          start = end;
        }
      return results;
    }
    

  • 0
    W

    Thanks.
    Here is my python code:

    class Solution(object):
        def summaryRanges(self, nums):
            """
            :type nums: List[int]
            :rtype: List[str]
            """
            res = []
            i = 0
            while i < len(nums):
                temp = nums[i]
                while i < len(nums)-1 and nums[i+1] - nums[i] == 1:
                    i += 1
                if temp != nums[i]:
                    res.append(str(temp) + "->" + str(nums[i]))
                else:
                    res.append(str(temp))
                i += 1
                    
            return res
    

Log in to reply
 

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