程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Leetcode[1984] python3 implementation of minimum difference of student scores (sorting, one-time traversal)

編輯:Python
# To give you one Subscript from 0 Start Array of integers for nums , among nums[i] It means the first one i A student's grade . I'll give you another integer k . 
# 
# Select any... From the array k A student's grade , Make this k Between scores The highest and Lowest score Of Difference value achieve To minimize the . 
# 
# Return possible Minimum difference . 
# 
# 
# 
# Example 1: 
# 
# Input :nums = [90], k = 1
# Output :0
# explain : elect 1 A student's grade , have only 1 Methods :
# - [90] The difference between the highest score and the lowest score is 90 - 90 = 0
# The smallest possible difference is 0
# 
# 
# Example 2: 
# 
# Input :nums = [9,4,1,7], k = 2
# Output :2
# explain : elect 2 A student's grade , Yes 6 Methods :
# - [9,4,1,7] The difference between the highest score and the lowest score is 9 - 4 = 5
# - [9,4,1,7] The difference between the highest score and the lowest score is 9 - 1 = 8
# - [9,4,1,7] The difference between the highest score and the lowest score is 9 - 7 = 2
# - [9,4,1,7] The difference between the highest score and the lowest score is 4 - 1 = 3
# - [9,4,1,7] The difference between the highest score and the lowest score is 7 - 4 = 3
# - [9,4,1,7] The difference between the highest score and the lowest score is 7 - 1 = 6
# The smallest possible difference is 2 
# 
# 
# 
# Tips : 
# 
# 
# 1 <= k <= nums.length <= 1000 
# 0 <= nums[i] <= 10⁵ 
# 
# Related Topics Array Sort The sliding window 66 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def minimumDifference(self, nums: List[int], k: int) -> int:
nums.sort()
return min(nums[i+k-1]-nums[i] for i in range(0, len(nums)-k+1))
# leetcode submit region end(Prohibit modification and deletion)

If you want to initialize a maximum integer , use float(‘inf’)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved