简体   繁体   English

如何为JAVA编写简单的主函数

[英]How to write a simple main function for JAVA

I am a beginner to JAVA. 我是JAVA的初学者。 I am doing the problem "insert intervals" in LeetCode. 我在本文给出了这样的问题,“插入时间间隔”。 Below is the problem. 下面是问题所在。

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 给定一组不重叠的间隔,请在间隔中插入一个新间隔(必要时合并)。

Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]." 示例1:给定间隔[1,3],[6,9],将[2,5]插入并合并为[1,5],[6,9]。”

Below is the code. 下面是代码。 But I don't know how to write a main function. 但是我不知道如何编写一个主要功能。 Anyone can help? 有人可以帮忙吗? Thank you very much! 非常感谢你!

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) {

    }
}

Assuming you just want to test the written method, this should help. 假设您只想测试书面方法,这应该会有所帮助。

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);
}

I hope the above code is self-explanatory. 我希望上面的代码是不言自明的。 I think you already have the class Interval defined. 我认为您已经定义了Interval类。 This is how it could look 这看起来像

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 + "]";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM