[leetcode 1]TwoSum

来源:互联网 发布:花生壳域名忘记了 编辑:程序博客网 时间:2024/05/17 22:31

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

UPDATE (2016/2/13):

The return format had been changed to zero-based indices. Please read the above updated description carefully.//原先索引从1开始,现在改成从0开始.

哈希表,先取出一个数,然后用target减去这个数得到gap,查找gap是否存在于之后的数组里.

最后返回一个vector<int>类型的索引.

vector<int> TwoSum(vector<int>&nums, int target){unordered_map<int, int >hashTable;vector<int>result;for (int i = 0; i < nums.size(); i++)hashTable[nums[i]] = i;//赋上坐标值for (int i = 0; i < nums.size(); i++) //i为取出值的坐标{const int gap = target - nums[i];if (hashTable.find(gap) != hashTable.end() && hashTable[gap]>i)//规定index0小于index1{result.push_back(i);result.push_back(hashTable[gap]);break;}}return result;}


0 0
原创粉丝点击