问题描述
在一个数组中找到两个角标元素,给定一个和值,返回
例如 arr = [11,2,3,5] ; 给定8; 返回2,3;
问题解答
常见的新手想法就是穷举两层循环进行遍历即可,那么这个题目就没什么出的意义了;这里给出一个复杂度是
程序
#include <iostream>
#include<vector>
using namespace std;
int binFind(int arr[],int startIndex, int endIndex, int temp);
vector<int> solution(int arr[],size_t size, int s);
int main() {
int arr[] = {23,1,2,3,4,5,8,91,100};
vector<int> vec = solution(arr,9,101);
if(vec.size() == 1)
cout<<"Not Find"<<endl;
else
cout << vec[0] <<","<<vec[1]<<endl;
return 0;
}
int binFind(int arr[],int startIndex, int endIndex,int temp){
int midIndex;
while(startIndex <= endIndex){
midIndex = (startIndex + endIndex)/2;
if(temp == arr[midIndex])
return midIndex;
else if(temp < arr[midIndex])
endIndex = midIndex -1;
else
startIndex = midIndex +1;
}
return -1;
}
vector<int> solution(int arr[],size_t size, int s){
vector<int> result;
for(int i=0;i< size - 1; ++i){
int k = i+1;
int next = arr[k];
while(k >-1 && arr[k-1] > next){
arr[k] = arr[k-1];
k--;
}
arr[k] = next;
//上面部分完成快排,下面部分完成s = A+B的寻找匹配
int ylable = binFind(arr,0,i,s-arr[i]);
if(!(ylable+1)){
result.push_back(i);
result.push_back(ylable);
return result;
}
}
result.push_back(-1);
return result;
}
后记
这个题目在知乎上偶然遇到,于是顺手解决了,贴上,起初自己使用python实现的,后来回来了用C++重新写了遍,若有错误之处,稍后改正。
python 实现
import numpy as np
def bFind(arr,start,end,temp):
while(start <= end):
mid = (int)((start + end)/2)
if(temp == arr[mid]):
return mid
else:
if (temp > arr[mid]):
start = mid +1
else:
end = mid -1
return -1
def sumk(arr,s):
for i in range(len(arr)-1):
next1 = arr[i+1]
k = i;
while(i>-1 & arr[k] > next1):
arr[k+1] = arr[k]
k = k-1
arr[k+1] = next1
ylable = s - arr[i]
temp = bFind(arr,0,i,ylable)
if(temp != -1):
return i,temp
return 'not find'
arr =np.array([1,2,3,45,61,72])
print('结果:',sumk(arr,156))