2023年5月15日 星期一

5/15 每日一題 (排除兩邊極端值)

 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.
class Solution:
    def average(self, salary: List[int]) -> float:
        '''定一兩個極端值指針'''
        n=len(salary)
        total=0
        i=0
        high,low=salary[i],salary[i]
        c=0
        while i < n-1:
            i +=1
            if high < salary[i]:
                high=salary[i]
            if low > salary[i]:
                low=salary[i]
        for i in range(n):
            if salary[i] != high and salary[i] != low:
                total += salary[i]
                c += 1
        return total /c

---------------------------------------------------
chatGPT優化後算法

def mea(salary):
    n=len(salary)
    total=0
   
    high,low=float('-inf'),float('inf')
    count=0
    for i in range(n):
        total += salary[i]
        high=max(high,salary[i]) #目前high被定義負無窮大, max(-無限,salary[i])
        low=min(low,salary[i])
        print(f'目前total={total}, high={high}, low={low}')
    total -=(high+low)
    return total/(n-2)
-----------------------------------------
也可以使用list中的sorted排列, 他會變成一組遞增list 加總後扣掉0和-1






標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁