【问题标题】:Given two lists V1 and V2 of sizes n and m respectively. Return the list of elements common to both the lists and return the list in sorted order给定两个大小分别为 n 和 m 的列表 V1 和 V2。返回两个列表共有的元素列表,并按排序顺序返回列表
【发布时间】:2021-09-14 06:24:27
【问题描述】:
class Solution {
    public static ArrayList<Integer> common_element(ArrayList<Integer>v1, ArrayList<Integer>v2) {
        ArrayList<Integer> com = new ArrayList<>();
        Collections.sort(v1);
        Collections.sort(v2);
        
        int i = 0;
        int j = 0;
        while (i < v1.size() && j < v2.size()) {
            if (v1.get(i) == v2.get(j)) {
                com.add(v1.get(i));
                i++;
                j++;
            } else if (v1.get(i) > v2.get(j)) {
                j++;
            } else {
                i++;
            }
        }
        return com;
    }
}

问题描述
Duplicates 可能在输出列表中。
我的代码有什么问题。当我运行它时,它会很容易且成功地编译,但是当我提交代码时,它显示无法正常工作,就像我的代码输出错误一样。
但它失败的地方,我无法理解。谁能帮我知道这个......!

【问题讨论】:

  • 欢迎来到堆栈。您有可用的调试器吗?您使用的是 Eclipse 还是 IntelliJ 之类的 IDE?

标签: java sorting arraylist


【解决方案1】:

您找到Common elements between given two Lists 的方法非常好。无法弄清楚为什么您没有得到正确的判决。
我建议您尝试以下修改并检查它是否有效。

    while (i < v1.size() && j < v2.size())
    {
        int x1 = v1.get(i), x2 = v2.get(j);
        if (x2 == x1)
        {
            com.add(x1);
            i++; j++;
        }
        else if (x1 > x2)
            j++;
        else 
            i++;
    }

如果上述方法有效,则表明您提交的平台可能存在问题,因为方法与您的完全相同。

【讨论】:

  • 它正在工作.....但不同之处在于--> int x1 = v1.get(i), x2 = v2.get(j);
【解决方案2】:

如果您在线提交,请阅读大多数在线比赛的规则,要求您的解决方案具有从文件或控制台读取输入并以特定格式输出的 main 方法。除此之外,您的解决方案看起来还不错。

【讨论】:

    猜你喜欢
    • 2019-03-16
    • 1970-01-01
    • 2022-07-30
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    相关资源
    最近更新 更多