如何为JAVA编写简单的主函数
我是JAVA的初学者。我正在LeetCode中处理“插入间隔”问题。下面是问题所在 给定一组不重叠的间隔,在间隔中插入一个新间隔(如有必要,合并) 例1: 给定区间[1,3]、[6,9],在as[1,5]、[6,9]中插入并合并[2,5] 下面是代码。但我不知道如何编写主函数。有人能帮忙吗?非常感谢!如何为JAVA编写简单的主函数,java,insert,intervals,Java,Insert,Intervals,我是JAVA的初学者。我正在LeetCode中处理“插入间隔”问题。下面是问题所在 给定一组不重叠的间隔,在间隔中插入一个新间隔(如有必要,合并) 例1: 给定区间[1,3]、[6,9],在as[1,5]、[6,9]中插入并合并[2,5] 下面是代码。但我不知道如何编写主函数。有人能帮忙吗?非常感谢! public class Solution { public List<Interval> insert(List<Interval> intervals, Interva
public class Solution {
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> res = new ArrayList<Interval>();
boolean inserted = false;
for (Interval it : intervals) {
if (inserted || it.end < newInterval.start) {
res.add(it);
} else if (it.start > newInterval.end) {
res.add(newInterval);
res.add(it);
inserted = true;
} else {
newInterval.start = Math.min(newInterval.start, it.start);
newInterval.end = Math.max(newInterval.end, it.end);
}
}
if (inserted == false) res.add(newInterval);
return res;
public static void main(String[] args) {
}
}
公共类解决方案{
公共列表插入(列表间隔,间隔newInterval){
List res=new ArrayList();
布尔插入=假;
for(Interval it:Interval){
if(插入的| | it.endnewInterval.end){
res.add(newInterval);
决议添加(it);
插入=真;
}否则{
newInterval.start=Math.min(newInterval.start,it.start);
newInterval.end=Math.max(newInterval.end,it.end);
}
}
if(inserted==false)res.add(newInterval);
返回res;
公共静态void main(字符串[]args){
}
}
假设您只想测试编写的方法,这应该会有所帮助
public static void main(String[] args) {
Solution solution = new Solution();
List<Interval> intervals = new ArrayList<>(); //Create list of intervals
intervals.add(new Interval(1, 3));
intervals.add(new Interval(6, 9));
List<Interval> mergedIntervals = solution.insert(intervals, new Interval(2, 5));
System.out.println(mergedIntervals);
}
非常感谢!这正是我需要的。我尝试过,但结果是“[insertInterval]。Interval@26f0a63f,插入区间。Interval@4361bd48]“。你能帮忙吗?真的很抱歉。我是新来的。你需要像我一样重写
toString
方法。我认为这是在线判断的一部分-看看你是否可以在Interval类中插入toString代码(如果允许编辑)
private class Interval {
int start;
int end;
public Interval(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public String toString() {
return "[" + start + "," + end + "]";
}
}