LeetCode -- Summary Ranges

呜呜呜~要感动cry了,提交了AC解答后,beats 100% of java submissions!!第一次感受到coding和algorithm带给人的愉悦感,加油加油啊~

Quesion:

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

Analysis:

这道题目的难点在于,要考虑很多种情况。

如{-1, 1,2, 3},{-1,1,3},{1,2,3,8}等等各种情况,还有时间空间复杂度。本来一个解决方案是想额外使用一个List<List<Integer>>链表,额外保存分层的一段段区间,但是后来感觉用指针完全可以解决问题,于是放弃了额外空间的打算。

Answer:

    public  List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<String>();
        String tem = "->";
        for(int i=0; i<nums.length; ) {
            String s = Integer.toString(nums[i]);
            if(i+1 == nums.length){ //i是最后一个单数字区间的情况
                res.add(s);
                return res;
            }
            int j = i + 1;
            while(j < nums.length) {
                if(nums[i] + 1 == nums[j] && j+1 == nums.length) { //区间一直到最后字符的情况
                    s = s + tem + Integer.toString(nums[j]);
                    res.add(s);
                    return res;
                }
                if(nums[i] + 1 == nums[j]) { //中间普通情况
                    i = j;
                    j++;
                }
                else { //开始出现断层的情况
                    if(i == 0) {  //第一个数字是单区间的情况
                        res.add(s);
                        i++;
                        break;
                    }
                    if(s.equals(Integer.toString(nums[i]))) { //中间某个数字是单区间的情况
                        res.add(s);
                        i++;
                        break;
                    }
                    s = s + tem + Integer.toString(nums[i]); //其他一般分层情况
                    res.add(s);
                    i = j;
                    break;
                }
            }
        }
        return res;
    }

 

posted @ 2015-09-09 10:14  江湖小妞  阅读(191)  评论(0编辑  收藏  举报