leetcode 908 Smallest Range I

Easy

题目:

Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].

After this process, we have some array B.

Return the smallest possible difference between the maximum value of B and the minimum value of B.

Example 1:

Input: A = [1], K = 0
Output: 0
Explanation: B = [1]
Example 2:

Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]
Example 3:

Input: A = [1,3,6], K = 3
Output: 0
Explanation: B = [3,3,3] or B = [4,4,4]

Note:

1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000

思路

思路很简单,就是先找到数组中的最大值与最小值,然后最小值加K,最大值减k,如果现在最大值还比最小值大,那最小差就是它俩差。如果最小值等于或者大于最大值,那他们最小差就是0.
下面是代码:
java

class Solution {
    public int smallestRangeI(int[] A, int K) {
        
        int min=A[0];
        int max=A[0];
        for(int i=0;i<A.length;++i)
        {
            if(A[i]>=max)
                max=A[i];
            if(A[i]<=min)
                min=A[i];
        }
        min=min+K;
        max=max-K;
        if(max>min)
            return max-min;
        else
            return 0;
        
        
    }
}

python

class Solution:
    def smallestRangeI(self, A: List[int], K: int) -> int:
        return max(0,max(A)-min(A)-2*K)
        
### LeetCode 215 的 Python 解法 对于 LeetCode 第 215 题,即寻找数组中的第 K 大元素,可以采用多种方法解决。其中一种高效的方法是利用快速选择算法 (Quickselect),这是基于快速排序的一种变体。 #### 方法一:使用内置函数 最简单的办法就是先对整个列表进行排序再选取倒数第 k 个位置上的数值: ```python class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: return sorted(nums)[-k] ``` 这种方法虽然简洁但是效率不高,在数据量较大时性能较差[^1]。 #### 方法二:堆排序 另一种方式是构建最大堆或最小堆来获取前 K 大的元素之一: ```python import heapq from typing import List class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: min_heap = [] for num in nums: if len(min_heap) < k or num > min_heap[0]: heapq.heappush(min_heap, num) if len(min_heap) > k: heapq.heappop(min_heap) return min_heap[0] if min_heap else None ``` 此方案的时间复杂度为 O(N log K), 更适合处理大规模的数据集[^2]. #### 方法三:快速选择 QuickSelect 最后推荐的是更高效的解决方案——快速选择算法。该算法平均情况下时间复杂度仅为O(n): ```python from random import randint from typing import List def partition(left, right, pivot_index, nums): pivot_value = nums[pivot_index] # Move pivot to end nums[pivot_index], nums[right] = nums[right], nums[pivot_index] store_index = left for i in range(left, right): if nums[i] < pivot_value: nums[store_index], nums[i] = nums[i], nums[store_index] store_index += 1 # Place pivot after the last smaller element nums[right], nums[store_index] = nums[store_index], nums[right] return store_index def select(left, right, k_smallest, nums): """ Returns the k-th smallest element of list within left..right. """ if left == right: # If the list contains only one element, return nums[left] # return that element. # Select a random pivot_index between pivot_index = randint(left, right) # Find the pivot position in a sorted list pivot_index = partition(left, right, pivot_index, nums) # The pivot is in its final sorted position if k_smallest == pivot_index: return nums[k_smallest] elif k_smallest < pivot_index: return select(left, pivot_index - 1, k_smallest, nums) else: return select(pivot_index + 1, right, k_smallest, nums) class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: # Convert to index-based by subtracting from length k = len(nums) - k return select(0, len(nums)-1, k, nums) ``` 上述代码实现了完整的 `findKthLargest` 函数以及辅助性的分区 (`partition`) 和选择 (`select`) 函数。通过随机化枢轴的选择过程提高了算法稳定性并减少了最坏情况发生的可能性[^4].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值