Reputation: 236
I have one function which takes 2 List as a parameter. The end result which we want is to check from the first list, How many elements are less than equals to each element from the second List?
For Example:
firstlist = [1,4,2,4]
secondList = [3,5]
Output = [2,4]
Explaination:
secondList[3] is >= firstList[1,2] So total is 2.
secondList[5] is >= firstList[1,4,2,4] so total is 4.
I have wrriten a solution but that is not optimize one.
public List<Integer> counts(List<Integer> teamA, List<Integer> teamB) {
// Write your code here
int[] b = teamB.stream().mapToInt(i -> i).toArray();
int[] a = teamA.stream().mapToInt(i -> i).toArray();
int counter;
List<Integer> goals = new ArrayList<>();
for (int i= 0;i<b.length;i++){
counter= 0;
for (int j =0;j < a.length; j++){
if (a[j] <= b[i]){
counter++;
}
}
goals.add(counter);
}
return goals;
}
Upvotes: 0
Views: 143
Reputation: 458
If you want to reduce the time complexity then you can sort the first list and for every element in the second list apply Binary search to find the numbers which are less.
This way the time complexity will be brought down from O(N*M)
to O(Mlog(N))
Upvotes: 3
Reputation: 2644
Use streams to simplify your code. If you're using lists, then stick to lists. Arrays are usually faster but harder to deal with.
public static List<Integer> counts(List<Integer> teamA, List<Integer> teamB) {
//Stream teamB and map each value to a result
return teamB.stream().map(b ->
//Result is count of elements from teamA that are <= b
(int) teamA.stream().filter(a -> a <= b).count()
).collect(Collectors.toList()); //Collect result stream into a list
}
Upvotes: 1