I have three string arrays at length 9 and I want to see if all of them include the same name. I have to do this in linearithmic time, O(NlogN). My plan is to sort two of the arrays and than use binarysearch to find similar names. My code is like this atm:
import edu.princeton.cs.algs4.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class Triplicate2_2_21 {
// arrays.binarysearh
public static void main(String[] args) {
//Strengir sem innihalda 9 nöfn. Sumir innihalda sama nafnið.
//Nöfn sem eru eins í öllum 3 listunum eru Hulda og Ingi.
String[] name1 = {"Helgi", "Arnar", "Hulda", "Hrefna", "Ingi", "Marta",
"Svavar", "Ester", "Valur"};
String[] name2 = {"Oddur", "Birgitta", "Hulda", "Ingi", "Selma", "Svavar",
"Sylvia", "Unnar", "Hrefna"};
String[] name3 = {"Elfa", "Jan", "Hulda", "Hrund", "Ingi", "Marta",
"Angela", "Sturla", "Valur"};
Arrays.sort(name2);
Arrays.sort(name3);
for(int i = 0; i < name1.length; i++) {
if((Arrays.binarySearch(name2,name1[i])).compareTo(Arrays.binarySearch(name3,name1[i])) < 0 ) {
StdOut.println(name1[i]);
break;
}}}}
I just want to print out the first triplicate I find, that´s why I do break. This code example is not working and I can´t figure out how to implement this idea further more. So, I´m here to seek out for your help to finish this.
P.s. this is a homework and the question is from the book Introduction to Algorithms, 4th edition, and sounds like this:
"Triplicates. Given three lists of N names each, devise a linearithmic algorithm to determine if there is any name common to all three lists, and if so, return the first".
compareTois what you need here. With your approach, I'd probably go forbinarySearch(..) >= 0 && binarySearch(..) >= 0, which also short circuits if the first condition isn't met.trueorfalse, with linear runtime. The second description yields element(s), with quadratic time if implemented naively