[LeetCode] Algorithm: Analysis of the solution of the sum of two numbers (twoSum)

Topic【Sum of two numbers】

Given an integer array numsand an integer target value target, please find the two integers in the array whose sum is the target value targetand return their subscripts.

Example 1:

输入:nums = {
    
    2,7,11,15}, target = 9
输出:{
    
    0,1}
解释:因为 nums[0] + nums[1] == 9, 返回[0,1]

Example 2:

输入:nums = {
    
    3,2,4}, target = 6
输出:{
    
    1,2}

Solution 1: Violent enumeration method

#include <iostream>
#include <vector>
using namespace std;

//暴力枚举
vector<int> twoSum(vector<int>& nums, int target)
{
    
    
    int n = nums.size();
    for (int i = 0; i < n; ++i)
    {
    
    
        for (int j = i + 1; j < n; ++j)
        {
    
    
            if (nums[i] + nums[j] == target)
            {
    
    
                return {
    
     i, j };
            }
        }
    }
    return {
    
    }; // 如果没有找到满足条件的组合,返回一个空数组
}

void printResult(vector<int> result)
{
    
    
    if (result.size() > 0)
    {
    
    
        cout << "result elem : {";
        for (auto i : result)
        {
    
    
            cout << " " << i << " ";
        }
        cout << "}" << endl;
    }
    else
    {
    
    
        cout << "result size : " << result.size() << endl;
    }
}

void test01()
{
    
    
    vector<int> nums = {
    
     2, 7, 11, 15 };
    int target = 9;

    vector<int> result = twoSum(nums, target);
    printResult(result);
}

void test02()
{
    
    
    vector<int> nums = {
    
     3,2,4 };
    int target = 6;

    vector<int> result = twoSum(nums, target);
    printResult(result);
}

int main()
{
    
    
    test01();
    test02();
    return 0;
}
//result
result elem : {
    
     0  1 }
result elem : {
    
     1  2 }

1. Time complexity analysis

  • The outer loop traverses from index 0 to n-1, where n is the length of the array, so there are n iterations.
  • The inner loop traverses from index i+1 to n-1, requiring n-1 iterations in the worst case.
  • Constant-time addition operations and comparison operations are performed in the inner loop.

Therefore, the overall time complexity of the brute force solution method isO(n^2) , where n is the length of the array.

2. Space complexity analysis

  • This algorithm uses no additional space other than the space to store the input array and output results.
  • The space complexity of the input array is O(n).
  • The space complexity of the output result is O(1) because the result is returned in the form of a return value.

Therefore, the overall space complexity of the brute force solution method isO(n) .

Although this method has a high time complexity, it can still be used for small-scale problems or when the input size is not large. However, for large-scale problems or when the input scale is large, the efficiency of this method will be low, so it is necessary to consider using other more optimized methods to solve the problem, such as hash tables, etc., to optimize the time complexity.


Solution 2: Hash table

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

vector<int> twoSum(vector<int>& nums, int target) 
{
    
    
    unordered_map<int, int> numMap;
    vector<int> result;

    for (int i = 0; i < nums.size(); i++) 
    {
    
    
        int complement = target - nums[i];

        if (numMap.find(complement) != numMap.end()) 
        {
    
    
            // 找到了满足条件的两个数
            result.push_back(numMap[complement]);
            result.push_back(i);
            break;
        }

        // 将当前数及其下标存入哈希表
        numMap[nums[i]] = i;
    }
    return result;
}

void printResult(vector<int> result)
{
    
    
    if (result.size() > 0)
    {
    
    
        cout << "result elem : {";
        for (auto i : result)
        {
    
    
            cout << " " << i << " ";
        }
        cout << "}" << endl;
    }
    else
    {
    
    
        cout << "result size : " << result.size() << endl;
    }
}

int main() 
{
    
    
    vector<int> nums = {
    
     2, 7, 11, 15 };
    int target = 9;

    vector<int> result = twoSum(nums, target);
    printResult(result);

    return 0;
}
//result
result elem : {
    
     0  1 }

The code uses a hash table to record each number and its corresponding subscript. As you iterate through the array, for each number, calculate the difference from the target value and then look in the hash table to see if that difference already exists. If it exists, it means that a combination of two numbers has been found, and its subscript is stored in the result array. If two numbers that satisfy the condition are not found after the traversal, an empty result array is returned.

1. Time complexity analysis

  • Traversing the entire array requires O(n) time complexity, where n is the length of the array.
  • The average time complexity of a lookup operation in a hash table is O(1).

Therefore, the overall time complexity of the hash table solution isO(n) .

2. Space complexity analysis

  • A hash table is used to store the elements in the array and their subscripts. In the worst case, the entire array of elements needs to be stored, so the space complexity is O(n).
  • The length of the array storing the results is at most 2, so the extra space consumption is negligible.

Therefore, the overall space complexity of the hash table solution isO(n) .

It should be noted that the above analysis is based on the worst-case complexity analysis, and the actual running time and space consumption will vary according to the characteristics of the input data. But under average circumstances, the lookup operation of the hash table has constant time complexity, so the overall time complexity is low.


If this article is helpful to you, I would like to receive a like from you!

Insert image description here

Supongo que te gusta

Origin blog.csdn.net/AAADiao/article/details/131426269
Recomendado
Clasificación