内容简介:Given a sorted integer array without duplicates, return the summary of its ranges.Example 1:Example 2:
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:
Input: [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
难度:medium
题目:给定 排序 且无重复元素的整数数组,返回其连续元素的范围。
思路:用以变量记录连续元素的开始。
Runtime: 5 ms, faster than 7.57% of Java online submissions for Summary Ranges.
Memory Usage: 37.5 MB, less than 5.02% of Java online submissions for Summary Ranges.
class Solution { public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList<>(); if (null == nums || nums.length < 1) { return result; } for (int i = 1, start = 0; i <= nums.length; i++) { if (i == nums.length || nums[i] - nums[i - 1] != 1) { result.add((i - 1 == start) ? String.format("%s", nums[start]) : String.format("%s->%s", nums[start], nums[i - 1])); start = i; } } return result; } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。