average-salaryV2.dart (790B)
1 //Better solution than sort solution where you iteate through 2 //the list one time tracking the highest and lowest vals. 3 //Then at the end subtract those from the total and return the mean. 4 //The time complexity of this code is O(n) where n is the length of the list 5 //Time: 260ms Beats: 80.77% 6 //Memory: 141.9MB Beats: 30.77% 7 class Solution { 8 double average(List<int> salary) { 9 int lowest = salary[0]; 10 int highest = salary[0]; 11 int total = 0; 12 for(int i = 0 ; i < salary.length ; ++i){ 13 if(salary[i] < lowest){ 14 lowest = salary[i]; 15 } 16 else if(salary[i] > highest){ 17 highest = salary[i]; 18 } 19 total += salary[i]; 20 } 21 total = total - (highest + lowest); 22 23 return total / (salary.length - 2); 24 } 25 }