Question

Write the method: List <Double> duplicates(List<Double> input) that returns a List of all duplicates in the...

Write the method:

List <Double> duplicates(List<Double> input)

that returns a List of all duplicates in the input List. You may assume that each element occurs either once or twice. The expected runtime must be O(n) where n is the number of elements (even if the input is a LinkedList, the runtime should still be O(n). Do not change the method header.

Examples:

input = [3, 4, 4] return [4]

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.*;

public class FindDuplicatesInList {

    List<Double> duplicates(List<Double> input) {
        List<Double> duplicates = new ArrayList<>();
        Map<Double, Integer> map = new HashMap<>();
        Iterator<Double> iterator = input.iterator();
        Double number;
        while (iterator.hasNext()) {
            number = iterator.next();
            if (map.containsKey(number)) {
                duplicates.add(number);
            } else {
                map.put(number, 0);
            }
        }
        return duplicates;
    }

    public static void main(String[] args) {
        LinkedList<Double> numbers = new LinkedList<>();
        numbers.add(3.0);
        numbers.add(4.0);
        numbers.add(4.0);

        System.out.println(new FindDuplicatesInList().duplicates(numbers));
    }
}
Add a comment
Know the answer?
Add Answer to:
Write the method: List <Double> duplicates(List<Double> input) that returns a List of all duplicates in the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT