【发布时间】:2021-10-28 05:19:25
【问题描述】:
问题如下:-
给定一个整数数组和一个整数目标,返回两个数字的索引,使它们加起来等于目标。 例如:-
Input: vec = [2,7,11,15], target = 9
Output: [0,1]
Output: Because vec[0] + vec[1] == 9, we return [0, 1].
我使用二进制搜索方法对问题进行了编码,我的主要看起来像这样:-
vector<int>vec = {2,7,11,15};
int flag = 0;
int target = 0,i;
int idx;
vector<int>::iterator it;
for(i=0;i<vec.size();i++)
{
if(binary_search(vec.begin()+i,vec.end(),target-vec[i]))
{
it = lower_bound(vec.begin()+i,vec.end(),target-vec[i]);
idx = it-vec.begin();
if (i!=idx)
{
flag = 1;
break;
}
}
}
if(flag==1)
{
cout<<"Found @"<<idx<<"and "<<i<<endl;
}
else{
cout<<"Not found";
}
它给出了正确的答案。
问题是,当我使用这种方法并从 Leetcode 中的函数返回答案向量(具有两个索引)时,它给了我这个错误:-
第 1034 行:字符 9:运行时错误:引用绑定到 类型'int'(stl_vector.h)摘要:UndefinedBehaviorSanitizer: 未定义行为 /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9
PS:- 为什么几乎没有人发布二进制搜索方法来解决这个问题?
【问题讨论】:
标签: c++ binary-search