首页 > 编程语言 > 详细

两数之和与目标值对比,相同则返回这两个数的数组下标。

时间:2021-07-19 14:57:31      阅读:34      评论:0      收藏:0      [点我收藏+]
//时间复杂度为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) :用空间换时间

两数之和与目标值对比,相同则返回这两个数的数组下标。

原文:https://www.cnblogs.com/0901-hcx/p/15028991.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!