【Leetcode】Summary Ranges
  iVhBmnbWORLX 2023年11月02日 61 0


题目链接:https://leetcode.com/problems/summary-ranges/

题目:

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

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

思路:

直接做就好了,时间复杂度O(n)

算法:


public List<String> summaryRanges(int[] nums) {
		List<String> result = new ArrayList<String>();
		if (nums.length == 1) {
			result.add(nums[0] + "");
			return result;
		}
		// 长度大于1时,因为要判断连续,至少要为2
		for (int i = 0; i < nums.length; i++) {
			int start = nums[i], j = i, end = i;
			for (int tmp = start; j < nums.length && nums[j] == tmp; j++, tmp++)
				;
			if (j == nums.length) { // 当j到了数组最后元素
				end = nums[j - 1];
			} else {// 当不连续
				end = nums[--j];
			}
			i = j;
			if ((end == start)) {
				result.add(start + "");
			} else {
				result.add(start + "->" + end);
			}
		}
		return result;
	}





【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  gBkHYLY8jvYd   2023年12月06日   44   0   0 #includecii++
  gBkHYLY8jvYd   2023年12月09日   26   0   0 cii++数据
  gBkHYLY8jvYd   2023年12月06日   19   0   0 cii++依赖关系
  gBkHYLY8jvYd   2023年11月19日   20   0   0 #includei++数据
  lh6O4DgR0ZQ8   2023年11月24日   13   0   0 cii++c++
  gBkHYLY8jvYd   2023年11月19日   20   0   0 i++测试数据数据
  gBkHYLY8jvYd   2023年11月22日   21   0   0 ioscii++
  gBkHYLY8jvYd   2023年12月10日   20   0   0 #include数组i++
  gBkHYLY8jvYd   2023年12月08日   16   0   0 #includecii++
  gBkHYLY8jvYd   2023年11月14日   25   0   0 #includei++升序
iVhBmnbWORLX