1.Two Sum 难度:easy

来源:互联网 发布:java后端是做什么的 编辑:程序博客网 时间:2024/05/22 04:39

题目:

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].

解题思路:

本题要我们在数组中找到两个数,要求两个数的和等于所给的数,输出两个数各自在数组中的位置。解题的关键是要建立数字和数字所在数组中的位置之间的关系,自然而然得联想到用stl容器map<int,int>。在遍历数组的过程中,在map中寻找target - nums[i],若找不到,则记录下当前数字所在数组的位置,若找到,则将找到的位置和当前位置保存在返回数组中,每次遍历一个位置要遍历一次map,因此算法的复杂度为O(n^2)。


程序:

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {                vector<int> res(2);map<int,int> m;for(int i = 0;i < nums.size();i++){if(m.find(target - nums[i]) == m.end())m[nums[i]] = i;else{res[0] = m[target - nums[i]];res[1] = i;break;}}return res;    }};




0 0
原创粉丝点击