【问题标题】:Code not generating expected output代码未生成预期输出
【发布时间】:2017-09-04 22:23:34
【问题描述】:

我正在尝试纠正我在面试中遇到的特定问题(问题是找到频率恰好为 f 的最小元素)。我想我已经在很大程度上设计了解决方案,但问题在于一些故障,这反过来又会产生一些错误的输出。我已经尝试了一切,检查并重新检查了代码,但问题仍然存在。由于我是 java 编程的初学者,因此对此不太了解,所以请帮助我。以下是我尝试过的:

public static int smallestKFreq(int a[], int n, int f)
    {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

        // Map is used to store the count of
        // elements present in the array
        for (int i = 0; i < n; i ++)

            if (map.containsKey(a[i]))
                map.put(a[i], m.get(a[i]) + 1);

            else map.put(a[i], 1);

        // Traverse the map and find minimum
        // element with frequency f.
        int res = Integer.MAX_VALUE;
        Set<Integer> s = map.keySet();

        for (int temp : s)
            if (map.get(temp) == f)
                res = Math.min(res, temp);

        return (res != Integer.MAX_VALUE)? res : 1;
    }

【问题讨论】:

  • “代码正在生成编译时错误” 什么编译时错误?!
  • 先生它正在生成不同的输出!!!{1,2,3,2,2,1,3} 然后输出是3
  • 所以...不是编译时错误。
  • 是的,先生,但预期的输出与原始输出不同!!!我的意思是说

标签: java arrays


【解决方案1】:

好的,所以看看你的问题,你似乎有错误的return 声明!!!

应该是

return (res !=Integer.MAX_VALUE)?res : -1;

试试这个,我认为它应该可以解决问题...

【讨论】:

  • 谢谢@mandy8055,它有效,但请告诉我为什么替换-1 有效?
  • @BaijNR 如果您已经理解了您编写的逻辑,那么它清楚地表明以最小值和最大频率返回结果,因此结果必须返回该元素或根本不返回任何内容......
猜你喜欢
  • 2017-09-15
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
  • 2023-02-12
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
相关资源
最近更新 更多