Note that there are some explanatory texts on larger screens.

plurals
  1. POReducing time complexity using HashMap, or is there a better method?
    primarykey
    data
    text
    <p>Right, this is from an older exam which i'm using to prepare my own exam in january. We are given the following method:</p> <pre><code>public static void Oorspronkelijk() { String bs = "Dit is een boodschap aan de wereld"; int max = -1; char let = '*'; for (int i=0;i&lt;bs.length();i++) { int tel = 1; for (int j=i+1;j&lt;bs.length();j++) { if (bs.charAt(j) == bs.charAt(i)) tel++; } if (tel &gt; max) { max = tel; let = bs.charAt(i); } } System.out.println(max + " keer " + let); } </code></pre> <p>The questions are:</p> <ol> <li>what is the output? - Since the code is just an algorithm to determine the most occuring character, the output is "6 keer " (6 times space)</li> <li>What is the time complexity of this code? Fairly sure it's O(n²), unless someone thinks otherwise?</li> <li>Can you reduce the time complexity, and if so, how?</li> </ol> <p>Well, you can. I've received some help already and managed to get the following code:</p> <pre><code>public static void Nieuw() { String bs = "Dit is een boodschap aan de wereld"; HashMap&lt;Character, Integer&gt; letters = new HashMap&lt;Character, Integer&gt;(); char max = bs.charAt(0); for (int i=0;i&lt;bs.length();i++) { char let = bs.charAt(i); if(!letters.containsKey(let)) { letters.put(let,0); } int tel = letters.get(let)+1; letters.put(let,tel); if(letters.get(max)&lt;tel) { max = let; } } System.out.println(letters.get(max) + " keer " + max); } </code></pre> <p>However, I'm uncertain of the time complexity of this new code: Is it O(n) because you only use one for-loop, or does the fact we require the use of the HashMap's get methods make it O(n log n) ?</p> <p>And if someone knows an even better way of reducing the time complexity, please do tell! :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload