반응형
https://leetcode.com/problems/smallest-range-i/description/
Smallest Range I - LeetCode
Can you solve this real interview question? Smallest Range I - You are given an integer array nums and an integer k. In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the ra
leetcode.com
min, max를 사용해 구현해보는 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
nums의 최솟값 minNum과 최댓값 maxNum를 선언 후 적절히 초기화해줍니다.
📔 풀이과정
1. nums의 원소를 순회하며 최댓값과 최솟값을 저장합니다.
2. 가장 적은 차이는 일반적으로 maxNum - k 에서 minNum + k를 뺀 값이 됩니다.
3. 해당값이 0이하라면 k가 범위이므로 적절한 조정으로 0을 만드는 것이 가능하다는 의미이므로 0을 반환해주면 됩니다.
4. 이외의 경우는 뺸 값을 반환하면 됩니다.
📕 Code
📔 C++
class Solution {
public:
int smallestRangeI(vector<int>& nums, int k) {
int minNum = 0x3f3f3f3f, maxNum = 0;
for(auto n : nums){
minNum = min(minNum, n);
maxNum = max(maxNum, n);
}
if(maxNum - k <= minNum + k) return 0;
return maxNum - k - (minNum + k);
}
};
📔 Rust
use::std::cmp;
impl Solution {
pub fn smallest_range_i(nums: Vec<i32>, k: i32) -> i32 {
let mut minNum = 0x3f3f3f3f;
let mut maxNum = 0;
for n in nums {
minNum = cmp::min(minNum, n);
maxNum = cmp::max(maxNum, n);
}
if maxNum - k <= minNum + k {
return 0;
}
return maxNum - k - (minNum + k);
}
}
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++, Rust) - LeetCode (easy) 925. Long Pressed Name (0) | 2023.09.04 |
---|---|
(C++, Rust) - LeetCode (easy) 922. Sort Array By Parity II (0) | 2023.09.01 |
(C++, Rust) - LeetCode (easy) 896. Monotonic Array (0) | 2023.08.22 |
(C++, Rust) - LeetCode (easy) 892. Surface Area of 3D Shapes (0) | 2023.08.18 |
(C++) - LeetCode (easy) 696. Count Binary Substrings (0) | 2023.08.10 |