LeetCode - 1984. Minimum Difference Between Highest and Lowest of K Scores(Array, Sorting)

YAMAMAMO·2022년 2월 8일
0

LeetCode

목록 보기
20/100

문제

0-indexed 정수 배열 num이 주어집니다. 여기서 nums[i]는 ith 학생의 점수를 나타냅니다. 또한 정수 k가 주어집니다.
배열에서 k 학생의 점수를 선택하여 k점 중 가장 높은 점수와 가장 낮은 점수의 차이를 최소화합니다.
가능한 최소 차액을 반환합니다.
https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/

You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k.
Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized.
Return the minimum possible difference.

Example 1:

Input: nums = [90], k = 1
Output: 0
Explanation: There is one way to pick score(s) of one student:

  • [90]. The difference between the highest and lowest score is 90 - 90 = 0.
    The minimum possible difference is 0.

Example 2:

Input: nums = [9,4,1,7], k = 2
Output: 2
Explanation: There are six ways to pick score(s) of two students:

  • [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
  • [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.
  • [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.
  • [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.
  • [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.
  • [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.
    The minimum possible difference is 2.

풀이

자바입니다.

  • 주어진 배열을 Array.sort()를 사용해서 오름차순으로 정렬합니다.
  • 0<=nums[i]<=10^5 범위입니다. 때문에 최소값 min=100000으로 선언합니다.
  • min 과 nums[i]-nums[i-k+1]를 비교해 최소값을 찾습니다.
class Solution {
    public int minimumDifference(int[] nums, int k) {
        if(nums.length==1)  return 0;
        
        Arrays.sort(nums);
        int min=100000;
        for(int i=nums.length-1;i>=0;i--){
            if(i-k+1>-1&&nums[i]-nums[i-k+1]<min) min=nums[i]-nums[i-k+1];
        }
        
        return min;
        
    }
}
profile
안드로이드 개발자

0개의 댓글