//时间复杂度为O(n^2) #include<iostream> #include<string> using namespace std; class Solution { public: int* twoSum( int arr[],int nums, int target) { for (int k = 0; k < nums; k++) { for (int j = k + 1; j < nums; j++) { int temp = arr[k] + arr[j]; if (temp == target) { int xb[2] = { k,j }; cout<<"The subscripts of these two numbers are:" ; cout<<xb[0]<<","<<xb[1]; return xb; } } } } }; int main() { Solution d; int arr[] = { 11,7,2,15 }; //cout<<arr[0]<<arr[1]; int nums=4; int target=9; int * p = d.twoSum(arr,nums,target); }
输出结果:
改进算法使得时间复杂度减小
改进思路:目标值和已知数组中的数据做差,利用字典数据类型将其存储到一个新的空间中,key是数组中的数据,value是该数据对应的数组下标,当与第二个数组中的数做差时,用差值与新字典中的数做对比,有相同,则返回此时的下标,没有相同则将数组中的第二个元素的数据及下标存在字典中,接着与数组中第三个数据作差,再与字典中的数作比较,以此循环做,直到遍历完数组。
改进后的时间复杂度为O(n) :用空间换时间