簡體   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