[LeetCode 1]Two Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cyrususie/article/details/89366540


Problem Link

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

Solution 1

Time complex: O ( n 2 ) O(n^2)
Space complex: O ( 1 ) O(1)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int numsLen = nums.size();
        for (int i = 0; i < numsLen; i++) {
            for(int j = i+1; j < numsLen; j++) {
                if (nums[i] + nums[j] == target) {
                    return {i, j};
                }
            }
        }
        return {};
    }
};

Solution 2

Time complex: O ( n ) O(n)
Space complex: O ( n ) O(n)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> computeAns;
        for (int i = 0; i < nums.size(); i++) {
            int complement = target - nums[i];
            if (computeAns.find(complement) != computeAns.end()) {
                return {computeAns[complement], i};
            }
            computeAns[nums[i]] = i;
        }
        return{};
    }
};

Summary

  • return{i, j} 是将i和j结合成一个vector返回的意思
  • unordered_map 要#include<unordered_map> 它的find函数返回的是对应元素的迭代器或者是unordered_map::end如果找不到此元素

猜你喜欢

转载自blog.csdn.net/cyrususie/article/details/89366540