Summary Ranges

    xiaoxiao2021-12-14  21

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

    参考率下别人的写法,用双指针,如果符合递增的条件,就++, 如果不符合,那么输入到result,有两种情况,只有一个元素跟有多个元素。加上之后需要更新pre cur 的index的位置。

    代码:

    public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList<>(); if(nums == null || nums.length == 0) return result; int pre = 0; int cur = 0; while(cur < nums.length){ if(cur<nums.length-1 && nums[cur+1] == nums[cur]+1){ cur++; }else{ if(pre == cur){ result.add(Integer.toString(nums[pre])); }else{ String str = nums[pre] + "->" + nums[cur]; result.add(str); } cur++; pre = cur; } } return result; }

    转载请注明原文地址: https://ju.6miu.com/read-971680.html

    最新回复(0)