chapter_searching/binary_search_edge/ #511
Replies: 18 comments 18 replies
-
啊,我太菜了,看了好几遍才看出来为什么要查找元素只出现一次也能找出来。。。。。 |
Beta Was this translation helpful? Give feedback.
-
如果数组元素是 []int 类型,那么查找右边界可以转化成查找左边界:要在数组中找到 target 的右边界,可以找 target+1 的左边界再来确定结果。 其他类型的话也可以用相同的思路,稍微麻烦点,比如 []string, 如果确定每个元素只含小写字母,要找 ‘abc’的右边界,可以先找 ‘abca' 的左边界。 |
Beta Was this translation helpful? Give feedback.
-
i,j的取值范围边界看了我好久,太妙了 |
Beta Was this translation helpful? Give feedback.
-
将查找最右一个 target 转化为查找最左一个 target + 1 这个妙啊 |
Beta Was this translation helpful? Give feedback.
-
我之前犯迷糊了,我没有意识到:查找左边界 查找右边界 是用2个函数完成的。 |
Beta Was this translation helpful? Give feedback.
-
在查找右边界判断时,nums[j] != target这句代码是不是可以省略呀~ |
Beta Was this translation helpful? Give feedback.
-
没有看懂,最左一个是target的话,为什么target+1是最右一个 |
Beta Was this translation helpful? Give feedback.
-
将查找最右一个target转化为查找最左一个target+1这个方法,是不是只有int类型可以这样做?像float类型的就只能用修改nums[m]==target时的边界操作来实现。不知道我理解的有没有问题 |
Beta Was this translation helpful? Give feedback.
-
这个target+1也太妙了,还有一些疑问,希望k神或其他小伙伴帮忙解答一下
|
Beta Was this translation helpful? Give feedback.
-
“请返回数组中最左一个元素 target 的索引”?感觉自己的阅读理解好差啊!感觉这句话表达的意思是“返回数组第一个元素的索引”。改成“请返回 target 元素在数组中的最左索引”是不是会好点啊 |
Beta Was this translation helpful? Give feedback.
-
https://leetcode.cn/problems/find-smallest-letter-greater-than-target/description/ |
Beta Was this translation helpful? Give feedback.
-
哈喽大家,关于target+1的我看了好久,一下是我的理解: :当传入target的时候,binarySearchInsertion 始终都会返回最左target的索引。当传入target + 1的时候则会返回最左target + 1的索引。当最左target + 1的索引 - 1便会得到最右target的索引。
我不确定我的理解到不到位,如果有误,希望大家可以多多给予指导哦 |
Beta Was this translation helpful? Give feedback.
-
请问关于转化为查找元素的实现是这样吗?😂 function binarySearchEdge(arr, target) {
let i = binarySearchInsertion(arr, target - 0.5); // 最左边界
let j = binarySearchInsertion(arr, target + 0.5) - 1; // 最右边界
if (i === arr.length || arr[i] !== target) i = -1;
if (j === -1 || arr[j] !== target) j = -1;
return { i, j }; // 返回对象 i & j
} |
Beta Was this translation helpful? Give feedback.
-
如何理解 target + 1的操作? |
Beta Was this translation helpful? Give feedback.
-
target + 1这个操作,其实打断点调试就容易明白了。 |
Beta Was this translation helpful? Give feedback.
-
因为target+1也可能有一堆相同的值。所以相当于111122222333这种排列。利用查找相同元素中的最左端函数,即一定有前一个元素的最右端与之相邻!而适用x+/-0.5,同理,这个不存在的元素的最左端一定与x的最右端相邻!(太酷啦orz |
Beta Was this translation helpful? Give feedback.
-
target+1,需要明白一点,target不是索引,是你要找的目标值,target+1实际上指的就是数组中比target大的下一个元素。计算这个元素的最左边界,减去1就是target的最右边界了。我的个人理解,如有错误,请多多指正 |
Beta Was this translation helpful? Give feedback.
-
chapter_searching/binary_search_edge/
一本动画图解、能运行、可提问的数据结构与算法入门书
https://www.hello-algo.com/chapter_searching/binary_search_edge/
Beta Was this translation helpful? Give feedback.
All reactions