leetcode Smallest Range II

本文探讨了如何通过增加或减去整数K来调整数组中每个元素,以最小化数组最大值与最小值之间的差距。提供了详细的算法解决方案及代码实现。

Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once).

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: 3
Explanation: B = [4,6,3]

Note:

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


Solution:
A[0]-K,A[0]+K

A[i]-K,A[i]+K
A[i+1]-K,A[i+1]+K

A[len-1]-K,A[len-1]+K

A[0]-K and A[len-1]+K won’t have effects in the final range. The final lower bound will be one of (A[0]+K, A[i]-K, A[i+1]-K) and the final upper bound will be one of (A[i]+K, A[i+1]+K, A[len-1]-K). But for different timestamp, the combination is different.
i=0, lower bound: (A[0]+K, A[1]-K) upper bound:(A[0]+K, A[len-1]-K)
i=1, lower bound: (A[0]+K, A[2]-K) upper bound:(A[1]+K, A[len-1]-K)

i=len-2, lower bound: (A[0]+K, A[len-1]-K) upper bound:(A[len-2]+K, A[len-1]-K)

So the code is:

class Solution:
    def smallestRangeII(self, A, K):
        la = len(A)
        if (la == 0):
            return 0
        A.sort()
        res = A[la-1]-A[0]
        for i in range(la-1):
            mi = min(A[0]+K,A[i+1]-K)
            ma = max(A[la-1]-K, A[i]+K)
            res = min(ma-mi, res)
        return res

Typical wrong idea is finding a median. We should come up with a bad case quickly and think towards the right way.

### 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].
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值