2009. Minimum Number of Operations to Make Array Continuous
You are given an integer array nums. In one operation, you can replace any element in nums with any integer.
nums is considered continuous if both of the following conditions are fulfilled:
- All elements in nums are unique.
- The difference between the maximum element and the minimum element in nums equals nums.length - 1.
For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.
Return the minimum number of operations to make nums continuous.
정수 배열 nums가 주어집니다. 한 번의 연산으로 nums의 모든 요소를 정수로 바꿀 수 있습니다.
nums는 다음 두 조건이 모두 충족되면 연속으로 간주됩니다.
-nums의 모든 요소는 고유합니다.
- nums의 최대 요소와 최소 요소의 차이는 nums.length - 1과 같습니다.
예를 들어, nums = [4, 2, 5, 3]은 연속이지만 nums = [1, 2, 3, 5, 6]은 연속이 아닙니다.
nums를 연속으로 만들기 위한 최소 연산 횟수를 반환합니다.
Example 1:
Input: nums = [4,2,5,3]
Output: 0
Explanation: nums is already continuous.
Example 2:
Input: nums = [1,2,3,5,6]
Output: 1
Explanation: One possible solution is to change the last element to 4.
The resulting array is [1,2,3,5,4], which is continuous.
Example 3:
Input: nums = [1,10,100,1000]
Output: 3
Explanation: One possible solution is to:
- Change the second element to 2.
- Change the third element to 3.
- Change the fourth element to 4.
The resulting array is [1,2,3,4], which is continuous.
Constraints:
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^9
코드
class Solution {
fun minOperations(nums: IntArray): Int {
val length = nums.size
val arr = nums.toSet().sorted()
var res = length
var r = 0
for (l in arr.indices) {
while (r < arr.size && arr[r] < arr[l] + length) {
r++
}
val window = r - l
res = minOf(res, length - window)
}
return res
}
}
'LeetCode > Sliding Window' 카테고리의 다른 글
[LeetCode][Kotlin] 992. Subarrays with K Different Integers (0) | 2024.11.22 |
---|---|
[LeetCode][Kotlin] 239. Sliding Window Maximum (0) | 2024.11.21 |
[LeetCode][Kotlin] 76. Minimum Window Substring (0) | 2024.11.18 |