https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/
Solution 1(My code)** 3ms** runtime
class Solution {
int countWords(String str){
if(str.length() == 0) {
System.out.println("0");
return 0;
}
int count = 0;
for(int i =0;i<str.length();i++){
if(str.charAt(i) == ' '){
count++;
}
}
return count+1;
}
public int mostWordsFound(String[] sentences) {
int max_words = 0;
for(int j =0;j<sentences.length;j++){
int count = countWords(sentences[j]);
if(count > max_words){
max_words = count;
}
}
return max_words;
}
}
Solution 2(Fastest solution according to leetcode through submissions tab) 1ms
class Solution {
public static int countWords(String str) {
if(str.length() == 0) {
System.out.println("0");
return 0;
}
int word = 0;
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) == ' ') {
word++;
}
}
return (word+1);
}
public int mostWordsFound(String[] sentences) {
int maxCount = 0;
for(int i = 0; i < sentences.length; i++){
int x = countWords(sentences[i]);
if(x > maxCount){
maxCount = x;
}
}
return maxCount;
}
}
can anyone tell me why the solutions is faster than solution 1
>Solution :
Both codes are identical, variables names are just different.
The answer is : the execution time is too low to differenciate performance here. The server of the website can have different load at the moment you submit or whatever, a few milliseconds is not enough to differenciate performance.
Also when talking about benchmark, code should run at least 100 or 1000 time (depending of the time you have of course) to get an average