admin 管理员组文章数量: 1087817
[勇者闯LeetCode] 1. Two Sum
[勇者闯LeetCode] 1. Two Sum
Description
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.
Information
- Tags: Array | Hash Table
- Difficulty: Easy
Solution
利用额外的map存储元素的值和位置。
Python Code
class Solution(object):def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""dictionary = {}for n, num in enumerate(nums):completement = target - numif completement in dictionary:return [n, dictionary[completement]]dictionary[num] = n
C++ Code
class Solution {
public:vector<int> twoSum(vector<int>& nums, int target) {unordered_map<int, int> lookup;for (int i = 0; i < nums.size(); i++) {if (lookup.count(target - nums[i])) {return {lookup[target - nums[i]], i};}lookup[nums[i]] = i;}return {};}
};
本文标签: 勇者闯LeetCode 1 Two Sum
版权声明:本文标题:[勇者闯LeetCode] 1. Two Sum 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1694406718a251696.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论