'Get the biggest number "n" in an array that occurs "n" times
Title sums it up.
For example {2,3,3,3,1} would return 3, {2,2,4,4,4} would return 2;
In my code I only get the biggest number that occurs n times. If 3 would occur 2 times and 2 would occur 2 times the program should return 2 but in my code it return 0.
public class arrays {
public static int NmalN(int[] arr) {
int max = 0;
int counter = 1;
for (int i=0; i<arr.length;) {
if (arr[i]>max) {
max = arr[i];
i++;
}
else i++;
}
for(int j = 0; j<arr.length; j++) {
if (arr[j]==max) {
counter++;
j++;
}
else {
j++;
}
}
if(max == counter) {
return counter;
}
else return 0;
}
public static void main(String[] args) {
int [] arr = {1,2,3,3,2,};
System.out.println("answer: "+ (NmalN(arr)));
}
}
Solution 1:[1]
As I read your code, you find the biggest number in the array, max. If that number occurs exactly max times, no more no less, you return it, otherwise you return 0. When 3 occurs only twice, you should probably try with 2, then with 1, etc. rather than just returning 0. Also think: is it OK if the number occurs more than max times?
Your loop for finding max looks fine (though convention would place i++ inside for (int i=0; i<arr.length; i++) and not inside the loop). After that you need a for loop to count down from max to 0, for each number n in that range checking if it occurs at least n times. You way of counting is almost correct, but as Vasan said in a comment, you are doing j++ both in for(int j = 0; j<arr.length; j++) and in the loop, that is, twice, so remove the one inside the loop. Whenever you find that counter >= n, return n. If not earlier, it will happen when n is 0, since 0 is always present 0 times.
Solution 2:[2]
import java.util.Arrays;
public class find_Biggest_Num_N_In_Array_Occures_N_times {
public static int Solution(int[] ar){
int[] counter= new int[ar.length];
Arrays.fill(counter, 0);
for(int i=0; i<ar.length;i++){
int pos=ar[i];
counter[pos]++;
}
for(int j=ar.length-1;j>=1;j--){
if(counter[j]==j){
return j;
}
}
return -1;
}
public static void main(String args[]){
System.out.println(Solution(new int[]{1,2,2,3,4,4,4,4,3,5,5,5,5,5,1}));
}
}
Solution 3:[3]
public static int solution(Integer[] intArray) {
int result = 0;
Arrays.sort(intArray, Collections.reverseOrder());
for (int i=0; i<intArray.length;i++) {
int count = 0;
for(int j=0;j<intArray.length;j++) {
if(intArray[i]==intArray[j]) {
count++;
}
}
if(count == intArray[i]) {
result = intArray[i];
break;
}
}
return result;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ole V.V. |
| Solution 2 | Rajan Domala |
| Solution 3 | Bala |
