繁体   English   中英

如何在数组中找到并打印在数组中恰好出现 K 次的最小数字,其中 K 是用户输入?

[英]How can i find and print the smallest number in array which occurs exactly K times in an array, where K is an user input?

我之前使用过嵌套方法,它给了我 TLE。 - 我们不能为此使用嵌套方法。 - 时间限制为 1 秒和 5000kb memory。 这是我的嵌套方法

for (int i = 0; i < n; i++) {
    if (arr[i] > 0) {
        int count = 1;
        for (int j = i + 1; j < n; j++)
            if (arr[i] == arr[j])
                count += 1;
        if (count == k)
            res = Math.min(res, arr[i]);
    }
}

您可以尝试使用一个字典来跟踪数字作为键,以及它作为值出现的次数。 这样,您只需通过阵列一次 go。

然后,最后检查哪些键的值为 K,并选择其中最小的。

首先,您应该获取最大元素并制作长度为 max+1 个元素的计数数组,即每个元素出现的时间例如:- arr=[2,5,1,2,3,6,3] 和 k=2。 现在计算每个元素,n是数组的长度,c是数组计数元素

int c[]=new int[max+1];
    for(int i=0;i<=max; i++)
    {
        c[a[i]]+=1;
    }
     Arrays.sort(a);
    //1 2 2 3 3 5 6
    for(int i=0;i<n;i++)
    {
        if(c[a[i]]==k)
        {
            System.out.print(a[i]);
            break;
        }
    }

这将为您提供所需的 output 时间复杂度 O(nLogn)

如何对数组进行排序,然后遍历它以返回出现 k 次的第一个值?

// return the smallest value that occurs k times, or null if none found
static Integer smallestK(int[] a, int k)
{
    Arrays.sort(a);

    for(int i=1, j=0; i<=a.length; i++)
    {
        if(i == a.length || a[i] != a[j])
        {
            if(i - j == k) 
                return a[j];
            j = i;
        }
    }
    return null;
}

测试:

int[] a = {6, 5, 3, 1, 4, 2, 5, 2, 2};

System.out.println(Arrays.toString(a));
for(int k=1; k<=4; k++)
{
    Integer val = smallestK(a.clone(), k);          
    if(val != null)
        System.out.format("k:%d, Result: %d%n", k, val);
    else
        System.out.format("k:%d, Not Found", k);
}

Output:

[6, 5, 3, 1, 4, 2, 5, 2, 2]
k:1, Result: 1
k:2, Result: 5
k:3, Result: 2
k:4, Not Found

您也可以尝试以下方法。 它具有 O(nlogn) 复杂度。

int[] arr1 = {10,2,15,20,25,4,25};//array
int k = 2;//minimum occurences
Arrays.sort(arr1);
HashMap<Integer,Integer> value = new HashMap<Integer, Integer>();
for(int i:arr1) {
    value.put(i, value.getOrDefault(i, 0)+1);
}
for(int i:arr1) {
    if(value.get(i)==k) {
        System.out.println(i);
        break;
    }
}

暂无
暂无

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

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