patternjavaMinor
Finding the value 'n' in an array that has 'n' or more larger values
Viewed 0 times
thelargerarraymorevaluehasthatfindingvalues
Problem
Given an unsorted array of integers, you need to return maximum possible \$n\$
such that the array consists at least \$n\$ values greater than or equals
to \$n\$. Array can contain duplicate values.
Sample 1
Sample 2
What do you folks think of my code to this problem?
such that the array consists at least \$n\$ values greater than or equals
to \$n\$. Array can contain duplicate values.
Sample 1
input : [1, 2, 3, 4]
output: 2Sample 2
input : [900, 2, 901, 3, 1000]
output: 3What do you folks think of my code to this problem?
public static Integer findN(Integer[] values) {
Comparator comparator = new Comparator() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
Arrays.sort(values, comparator);
for (int i = 0 ; i = values[i]) {
return values[i];
}
}
return Integer.MIN_VALUE;
}Solution
Right now, after you sort the array, you're doing a linear search for the correct value. I believe you should be able to write that part of the task using a binary search instead of a linear search.
The sorting has a minimum complexity of \$O(N log N)\$, so reducing the search from \$O(N)\$ to \$O(log N)\$ won't affect the overall computational complexity, but for any more than a small number of items, it should still reduce the overall time.
The sorting has a minimum complexity of \$O(N log N)\$, so reducing the search from \$O(N)\$ to \$O(log N)\$ won't affect the overall computational complexity, but for any more than a small number of items, it should still reduce the overall time.
Context
StackExchange Code Review Q#54881, answer score: 8
Revisions (0)
No revisions yet.