开始刷leetcode day71:Summary Ranges

来源:互联网 发布:js权威指南第七版pdf 编辑:程序博客网 时间:2024/06/06 01:26

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"].

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.



Java:

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList<String>();
        if(nums.length ==0) return result;
        int record = nums[0];
        int front = nums[0];
        boolean haslink = false;
        for(int i=1; i< nums.length; i++)
        {
            if(nums[i] != front + 1)
            {
                if(haslink)
                {
                    result.add(record + "->" + front);
                }else
                {
                    result.add(front+"");
                    
                }
                haslink = false;
                front = nums[i];
                record = front;
            }else
            {
                haslink = true;
                front = nums[i];
            }
        }
        if(haslink) result.add(record + "->" + front);
        else    result.add(front+"");
        
        return result;
        
    }
}

0 0
原创粉丝点击