We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
For anyone having trouble in Java:
I have yet to optimize this but I was able to pass all test cases except the last one (TestCase 3):
publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */List<Float>arr=newArrayList<>();Scannersc=newScanner(System.in);while(sc.hasNext()){floatf=sc.nextFloat();arr.add(f);}intsize=arr.size()-1;arr.remove(0);// remove first element because it's just size of arrayfloatmean=0;floatmedian=0;floatmode=0;// Sort arrayCollections.sort(arr);// Calculate meanfor(inti=0;i<arr.size();i++){mean+=arr.get(i);}mean=(mean/arr.size());System.out.println(mean);// Print out mean// Calculate median if(arr.size()%2==0){floatnum1=arr.get((int)(arr.size()/2));floatnum2=arr.get((int)(arr.size()/2)-1);median=((num1+num2)/2);}else{median=arr.get(((int)arr.size()/2)+1);}System.out.println(median);// Print out median// Calculate modeMap<Float,Integer>modeMap=newTreeMap<>();for(floatf:arr){if(modeMap.containsKey(f)){intcount=modeMap.get(f);modeMap.replace(f,count++);}else{modeMap.put(f,0);}}intcount=1;// counter to exit loopfor(Map.Entry<Float,Integer>entry1:modeMap.entrySet()){while(count<arr.size()){for(Map.Entry<Float,Integer>entry2:modeMap.entrySet()){if(entry1.getValue()>=entry2.getValue()&&entry1.getKey()<entry2.getKey()){mode=entry1.getKey();break;}elseif(entry1.getKey()==entry2.getKey()){mode=entry1.getKey();}count++;}}}System.out.println(mode);// Print out mode}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 0: Mean, Median, and Mode
You are viewing a single comment's thread. Return to all comments →
For anyone having trouble in Java: I have yet to optimize this but I was able to pass all test cases except the last one (TestCase 3):