//时间复杂度为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); }
输出结果:
改进算法使得时间复杂度减小
原文:https://www.cnblogs.com/0901-hcx/p/15028991.html