简体   繁体   English

排序数组中元素的上限

[英]Ceiling of the element in sorted array

Hi I am doing DSA problems and found a problem called as ceiling of the element in sorted array.嗨,我正在做 DSA 问题,并发现了一个问题,称为排序数组中元素的上限。 In this problem there is a sorted array and if the target element is present in the sorted array return the target.在这个问题中有一个排序数组,如果目标元素存在于排序数组中,则返回目标。 If the target element is not found in the sorted array we need to return the smallest element which is greater than target.如果在排序后的数组中找不到目标元素,我们需要返回大于目标的最小元素。 I have written the code and also done some test cases but need to check if everything works correctly.我已经编写了代码并做了一些测试用例,但需要检查一切是否正常。 This problem is not there on leetcode where I could run it with many different cases. leetcode 上不存在这个问题,我可以在许多不同的情况下运行它。 Need suggestion/feedback if the problem is solved in the correct way and if it would give correct results in all cases如果问题以正确的方式解决并且在所有情况下都能给出正确的结果,需要建议/反馈

class Solution:
    #My approch
    def smallestNumberGreaterThanTarget(self, nums, target):
        start = 0
        end = len(nums)-1

        if target > nums[end]:
            return -1
        while start <= end:
            mid = start + (end-start)//2

            if nums[mid] == target:
                return nums[mid]
            elif nums[mid] < target:
                if nums[mid+1] >= target:
                    return nums[mid+1]
                start = mid + 1
            else:
                end = mid-1

        return nums[start]

The code errors out with an index out-of-range error for the empty list (though this may not be necessary because you haven't specified the problem constraints).代码错误并出现空列表的索引超出范围错误(尽管这可能不是必需的,因为您尚未指定问题约束)。

A simple if guard at the top of the function can fix this: function 顶部的简单if防护可以解决此问题:

if not nums:
    return -1

Otherwise, it seems fine to me.否则,对我来说似乎很好。 But if you're still not sure whether or not your algorithm works, you can always do random testing (eg create a linear search version of the algorithm and then randomly generate inputs to both algorithms, and then see if there's any difference).但是如果您仍然不确定您的算法是否有效,您可以随时进行随机测试(例如,创建算法的线性搜索版本,然后随机生成两种算法的输入,然后查看是否有任何差异)。

Here's a one-liner that you can test against:这是您可以测试的单线:

input_list = [0, 1, 2, 3, 4]
target = 0
print(next((num for num in input_list if num >= target), -1))

IMO, the problem can be solved in a simpler way, with only one test inside the main loop. IMO,这个问题可以用一种更简单的方法来解决,在主循环中只需要一个测试。 The figure below shows a partition of the real line, in subsets associated to the values in the array.下图显示了实线的一个分区,在与数组中的值关联的子集中。

在此处输入图像描述

First, we notice that for all values above the largest, there is no corresponding element, and we will handle this case separately.首先,我们注意到对于所有大于最大值的值,没有对应的元素,我们将单独处理这种情况。

Now we have exactly N subsets left, and we can find the right one by a dichotomic search among these subsets.现在我们只剩下 N 个子集了,我们可以通过在这些子集中进行二分搜索找到正确的子集。

if target > nums[len(nums)-1]:
    return None

s, e= 0, len(nums);
while e > s:
    m= e + ((s - e) >> 1);
    if target > nums[m]:
        s= m
    else:
        e= m
return s

We can formally prove the algorithm using the invariant nums[s-1] < target <= nums[e] , with the fictional convention nums[-1] = -∞ .我们可以使用不变量nums[s-1] < target <= nums[e]正式证明该算法,虚构约定nums[-1] = -∞ In the end, we have the bracketing nums[s-1] < target <= nums[s] .最后,我们得到了括号nums[s-1] < target <= nums[s]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查找排序数组中元素的索引 - Finding Index of element in sorted array 查找已排序和旋转数组中的最小元素 - Find the minimum element in a sorted and rotated array 查找将元素插入已排序数组的位置 - Find the position to insert an element into a sorted array 以升序连接N个数组排序元素形成的第K个元素 - Kth element formed by joining N array sorted element in ascending order 对于一个已排序的 numpy 数组中的每个元素,如何减去另一个已排序数组中的最小较大值 - For each element in one sorted numpy array, how to subtract the smallest greater value in another sorted array 为什么在使用冒泡排序时未对数组的最小元素进行排序? - Why the minimum element of array is not sorted while using bubble sort? "在排序数组中查找 Pivot 元素,如何优化此代码?" - Finding Pivot element in a sorted array, How do I optimize this code? 查找数组中的最大元素,先升序再降序 - Finding the max element in an array, sorted ascending first and then descending 如何在排序数组中找到元素的 *unsorted* 位置? - How do I find the *unsorted* location of an element in a sorted array? 如何快速比较ndarray的每个元素和排序列表/数组的每个元素? - How to quickly compare every element of an ndarray with every element of a sorted list/array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM