简体   繁体   中英

Given an array find number such that the value of a number equals the number of times it occurs. What can we the most optimal solution for this?

I have an Java assignment which has the question below:

Given an array find number such that the value of a number equals the number of times it occurs. Can anyone suggest an optimal solution for it? I have written the solution below:

private static int number(int[] arr) {

    Map<Integer, Integer> map = new HashMap<>();

    for(int i=0; i<arr.length; i++) {
        map.put(arr[i], map.getOrDefault(arr[i], 0)+1);
    }

    for(int i=0; i<arr.length; i++) {
        if(map.get(arr[i]) == arr[i])
            return arr[i];
    }

    return -1;

}

You can first loop over the array once to create a frequency Map , and then check each entry.

int[] arr = {1, 1, 2, 3, 2, 2, 3, 3, 4};
Map<Integer, Integer> freq = Arrays.stream(arr).boxed()
    .collect(Collectors.toMap(x -> x, x -> 1, Integer::sum));
for(Map.Entry e: freq.entrySet()){
    if(e.getValue().equals(e.getKey())) System.out.println(e.getKey());
}

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