简体   繁体   中英

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?

I've earlier used nested approach which is giving me TLE. -we can not use nested approach for this. - time limit is 1 sec and 5000kb memory. Here is my nested approach

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

You can try using a dictionary that keeps track of the numbers as keys, and the number of times it appears as the value. This way you will only have to go through the array once.

Then, at the end you check which keys have a value of K, and choose the smallest of those.

Firstly you should get the max element and make count array of length max+1 elements ie how much time each elements occurring eg:- arr=[2,5,1,2,3,6,3] and k=2. Now count each element, n is length of array, c is array counting element

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

This will give you desired output with time complexity O(nLogn)

How about just sorting the array and then walking through it to return the first value that occurs k times?

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

Test:

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

You can try below approach as well. it has O(nlogn) complexity.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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