1491. Average Salary Excluding the Minimum and Maximum Salary (C++)

2022. 8. 17. 23:29STUDY/LeetCode

반응형

You are given an array of unique integers salary where salary[i] is the salary of the ith employee.

Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.

Example 1:

Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500

Example 2:

Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000

 

Constraints:

  • 3 <= salary.length <= 100
  • 1000 <= salary[i] <= 106
  • All the integers of salary are unique.

항상 문제를 잘 읽어야한다. ^^  최소값과 최대값을 제외한 !!!!!! 걸로 평균을 내야한다. ㅋㅋㅋ 아오 졸려 ㅠ 

쉬운 문제이지만, 이렇게 하나하나 풀어가면서 사용되는 함수들을 배울 수 있는 기회인것같다.

어거지로 함수만 배우려면 귀찮은데 이렇게 문제 풀면서 접하니까 자연스럽고 좋다. 

여기서는 vector 배열의 합을 구하는 함수인 accumulate 를  만났다. (이건 나중에 따로 포스팅 할 예정 !)

# 풀이 #

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
 
double average(vector<int>& s) {
    return ((double)accumulate(begin(s), end(s), 0- *min_element(begin(s), end(s)) 
        - *max_element(begin(s), end(s))) / (s.size() - 2);
}
 
double average(vector<int>& salary) {
        double aa1 = (double)accumulate(salary.begin(), salary.end(), 0);
        double min = *min_element(salary.begin(), salary.end()); 
        double max = *max_element(salary.begin(), salary.end());
        
        return (aa1 -(min+max))/(salary.size()-2);
    }
}
cs

저렇게 한줄짜리 return 값으로 푸는 인간들이 많은데 (ㅠㅠ) , 이해를 돕기위해 아래처럼 3줄짜리로 풀어봤다.

먼저 배열의 합을 구하고, 배열에서의 최소/최대값을 구하고, 

결과값은 전체 배열합 - (최소+최대) / (전체배열사이즈-2) 이다.

2 빼주는건 최소 / 최대 값을 제외하기 위해서겠쥬!?!?!?!?!? 

 

728x90
반응형

'STUDY > LeetCode' 카테고리의 다른 글

977. Squares of a Sorted Array  (1) 2022.08.21
278. First Bad Version  (0) 2022.08.21
26. Remove Duplicates from Sorted Array ( C++ )  (0) 2022.08.17
2000. Reverse Prefix of Word (C++)  (1) 2022.08.11
1678. Goal Parser Interpretation (C/C++)  (2) 2022.08.04