228. Summary Ranges

一、题目

  1、审题

  

  2、分析

    给出一个有序的无重复的整形数组,返回一个描述数组‘概要’的字符串 List。

 

二、解答

  1、思路

    方法一、

      采用两个指针记录前后的元素是否连续。

  

    public List<String> summaryRanges(int[] nums) {
    
        int len;
        List<String> list = new ArrayList<String>();
        if(nums == null || (len = nums.length) == 0)
            return list;

        int cur = 0, pre = 0;
        for (int i = 1; i < len; i++) {
            if(nums[i] == nums[i - 1] + 1) {
                cur = i;
            }
            else {
                if(cur == pre)
                    list.add(nums[pre] + "");
                else 
                    list.add(nums[pre] + "->" + nums[cur]);
                cur = pre = i;
            }
        }
        // the last one
        if(cur == pre)
            list.add(nums[pre] + "");
        else 
            list.add(nums[pre] + "->" + nums[cur]);
        return list;
    }

 

  方法二、

    直接以当前元素为每一个组合的起始,求出每一个组合。

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

 

posted @ 2018-11-07 20:21  skillking2  阅读(119)  评论(0编辑  收藏  举报