LeetCode--Two Sum

来源:互联网 发布:php printf函数 编辑:程序博客网 时间:2024/06/07 02:42
题目描述:

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.

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
解读:给予一组整型数组和一个目标整数,从数组中找到两个整数使得相加和为目标整数,并输出这两个整数的下标。
思路:①最简单的是遍历两次数组,复杂度为O(n²)
思路:②如果利用Map来替代第二次遍历,复杂度下降为O(n);
#include<iostream>  #include<vector> #include<map>class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> answer;        map<int, int> maps;        for(int i = 0; i <nums.size(); i++) {            maps[nums[i]] = i;        }        for(int i = 0; i < nums.size(); i++) {            int gap = target - nums[i];            if(maps.find(gap) != maps.end() && maps.find(gap)->second != i) {                answer.push_back(i);                answer.push_back(maps.find(gap)->second);                return answer;            }        }    }};


原创粉丝点击