本文介绍了Java - 适用于搜索间隔的数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java的新手,我想知道什么是最好的数据结构,我如何搜索我的案例的数据结构:
我有int间隔,例如: 10-100,200-500,1000-5000,对于每个间隔,我有一个值1,2,3,4。
我想知道如何将所有这些间隔及其值保存在数据结构中并且如何搜索该数据结构以返回特定间隔的值。
例如如果我搜索15,那是间隔10-100,我想返回1。
I'm new to Java and i would like to know what is the best data structure and how can i search through that data structure for my case:I have int intervals eg: 10-100, 200-500, 1000-5000 and for each interval i have a value 1, 2, 3, 4.I would like to know how can i save all those intervals and their values in a data structure and how can i search through that data structure to return the value for the specific interval.Eg. if i search 15, that is in interval 10-100, i would like to return 1.
谢谢
推荐答案
我将使用这种方式:
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class IntervalsTest {
@Test
public void shouldReturn1() {
Intervals intervals = new Intervals();
intervals.add(1, 10, 100);
intervals.add(2, 200, 500);
int result = intervals.findInterval(15);
assertThat(result, is(1));
}
@Test
public void shouldReturn2() {
Intervals intervals = new Intervals();
intervals.add(1, 10, 100);
intervals.add(2, 200, 500);
int result = intervals.findInterval(201);
assertThat(result, is(2));
}
}
class Range {
private final int value;
private final int lowerBound;
private final int upperBound;
Range(int value, int lowerBound, int upperBound) {
this.value = value;
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
boolean includes(int givenValue) {
return givenValue >= lowerBound && givenValue <= upperBound;
}
public int getValue() {
return value;
}
}
class Intervals {
public List<Range> ranges = new ArrayList<Range>();
void add(int value, int lowerBound, int upperBound) {
add(new Range(value, lowerBound, upperBound));
}
void add(Range range) {
this.ranges.add(range);
}
int findInterval(int givenValue) {
for (Range range : ranges) {
if(range.includes(givenValue)){
return range.getValue();
}
}
return 0; // nothing found // or exception
}
}
这篇关于Java - 适用于搜索间隔的数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!