当前位置: 代码迷 >> 综合 >> LeetCode228.Summary Ranges 解题
  详细解决方案

LeetCode228.Summary Ranges 解题

热度:85   发布时间:2023-12-10 03:00:28.0

 228.Summary Ranges
Difficulty: Medium
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"].

1. 解法,最简单,遍历判断。

public class Solution {public List<String> summaryRanges(int[] nums) {int length = nums.length;List<String> result = new ArrayList<String>();if (length == 0) {return result;}int start = nums[0];int theoreticalValue = start + 1;for (int index = 0; index < length; index ++) {if (index == length - 1) {if (nums[index] == (theoreticalValue - 1) && start != nums[index]) {String item = start + "->" + nums[index];result.add(item);} else {String item = "" + nums[index];result.add(item);}} else if(nums[index + 1] != theoreticalValue) {if (start == nums[index]) {String item = "" + nums[index];result.add(item);start = nums[index + 1];theoreticalValue = start;} else {String item = start + "->" + nums[index];result.add(item);start = nums[index + 1];theoreticalValue = start;}}theoreticalValue ++;}return result;}
}

 
 
虽然这个算法简单,当是并没有很好的效率,至打败了5.3%的java提交,这个题目本身不难,但是基本分成三类 ,好像是在第二类?好吧,其实用Python有更加就简单的方法。