leetcode--1. Two Sum

来源:互联网 发布:商标r和tm的区别 知乎 编辑:程序博客网 时间:2024/05/21 06:43

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].
class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> ans;    ans.clear();        unordered_map<int, int> hash; hash.clear(); //map的查询操作是logn,但是unordered_map的查询操作复杂度是常数级别        //所以下面这个算法复杂度是O(n)级别        for(int i = 0; i < nums.size(); i++) {            int tmp = target - nums[i];            if(hash.find(tmp) != hash.end()) {                ans.push_back(hash[tmp]);                ans.push_back(i);                return ans;            }            hash[nums[i]] = i;        }        return ans;    }};