[Leetcode] Two Sum

来源:互联网 发布:二维数组的长度 编辑:程序博客网 时间:2024/06/05 13:30

描述

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.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

分析

给定一个整型数组,找到两个数,使得它们的和为 target,返回这两个数的索引(假设有且仅有一组解)。

很自然的一个想法是暴力搜索[代码1],但是时间复杂度是 O(n2)

另外一种思路[代码2]:使用 map,建立起 “数值-索引”的对应关系。首先遍历一遍数组,完成 map 的初始化,之后再遍历一遍数组,同时在 map 中查找 target-nums[i],找到则返回对应索引,时间复杂度 O(n)

代码1

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

代码2

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int, int> m;        for (int i = 0; i < nums.size(); i++) {            if (m.count(target - nums[i])) return {i, m[target - nums[i]]};            m[nums[i]] = i;        }        return {};    }};
0 0
原创粉丝点击