2021.05.12寻找右区间

本文提供了一道LeetCode上的编程题目“寻找右区间”的两种解决方案:一种使用排序的方法,另一种采用Hashmap来实现。排序方法通过遍历并比较区间的起点和终点来找到符合条件的右区间;而Hashmap方法则是先将区间与索引映射存储,再进行排序查找。

2021.05.12寻找右区间

(题目来源:leetcode)

题目描述

有一组区间,定义区间i的“右区间”为这组区间中起点比区间i的终点大的区间,并且起点离区间i终点最近。

思路

思路1 排序

可通过排序后做

思路1 代码

	public int[] findRightInterval(int[][] inls) {
		int n = inls.length;
		int[] res = new int[n];	
		Arrays.fill(res, -1);
		Inl[] inl = new Inl[n];
		for(int i = 0; i < n; i++) inl[i] = new Inl(inls[i][0], inls[i][1],i);
		Arrays.sort(inl);
		for(int i = 0; i < n; i++) {
			for(int j = i+1; j < n; j++) {
				if(inl[j].s >= inl[i].e) {
					res[inl[i].i] = inl[j].i;
					break;
				}
			}
		}
		return res;
	}

	class Inl implements Comparable<Inl>{
		int s,e,i;
		public Inl(int s, int e, int i) {
			super();
			this.s = s;
			this.e = e;
			this.i = i;
		}
		public int compareTo(Inl o) { //按照起点升序排列
			return this.s-o.s;
		}
	}

思路2 Hashmap

	public int[] findRightInterval_hashMap(int[][] inls) {
		int n = inls.length;
		int[] res = new int[n];	
		Map<int[],Integer> map = new HashMap<int[], Integer>();
		for(int i = 0; i < n; i++) map.put(inls[i], i);
		Arrays.sort(inls, new Comparator<int[]>() {
			public int compare(int[] o1, int[] o2) {
				return o1[0]-o2[0];
			}
		});
		for(int i = 0; i < n; i++) {
			res[map.get(inls[i])] = -1;
			for(int j = i; j < n; j++) {
				if(inls[i][1] <= inls[j][0]) {
					res[map.get(inls[i])] = map.get(inls[j]);
					break;
				}
			}
		}
		return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值