Arrays分类算法-Largest Range

题目要求

在这里插入图片描述

解法一:
可以通过sort的方式,简单找出最长的连续的序列。但是本题不可sort。因此为了查找高效,采用hashMap来存已知数字,别对数字是否被用过进行标记,分别向前和向后找出存在的连续序列。
Time: O(n) Space: O(n)
代码1:

import java.util.*;

class Program {
  public static int[] largestRange(int[] array) {
    // Write your code here.
		if (array == null || array.length == 0) return new int[]{};
		HashMap<Integer, Boolean> map = new HashMap<>();
		int[] res = new int[2];
		int[] temp = new int[2];
		for (int num : array) {
			map.put(num, true);
		}
		for (int i = 0; i < array.length; i++) {
			if (map.get(array[i])) {
				map.put(array[i], false);
				int num = array[i] - 1;
				temp[0] = array[i];
				temp[1] = array[i];
				while (map.containsKey(num)) {
					map.put(num, false);
					temp[0] = num;
					num--;
				} 
				num = array[i] + 1;
				while (map.containsKey(num)) {
					map.put(num, false);
					temp[1] = num;
					num++;
				}
				if ((temp[1] - temp[0]) >= (res[1] - res[0])) {
					System.arraycopy(temp, 0, res, 0, 2);
				}
			} 
		}
    return res;
  }
}

代码2(写法简化):

import java.util.*;

class Program {
   public static int[] largestRange(int[] array) {
    // Write your code here.
		if (array == null || array.length == 0) return new int[]{};
		HashMap<Integer, Boolean> map = new HashMap<>();
		int[] res = new int[2];
		int longest = 0;
		for (int num : array) {
			map.put(num, true);
		}
		for (int num : array) {
			if (map.get(num)) {
				map.put(num, false);
				int left = num - 1;
				int right = num + 1;
				int tempLongth = 1;
				while (map.containsKey(left)) {
					map.put(left, false);
					tempLongth++;
					left--;
				} 
				while (map.containsKey(right)) {
					map.put(right, false);
					tempLongth++;
					right++;
				}
				if (tempLongth > longest) {
					longest = tempLongth;
					res = new int[]{left + 1, right - 1};
				}
			} 
		}
    return res;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值