标签:i++ order def and leetcode target div style 重复
1、Two Sum
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].
思路:
关键词:一遍迭代map
建立map,迭代一遍数组,第一个迭代开始检查numToFind是否存在于map中。存在就返回两者的index;
不存在就把当前的数组nums[i]插入到map。重复迭代下去。
C++:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; unordered_map<int,int> hash_map; for(int i=0;i<nums.size();i++) { int numToFind=target-nums[i]; if(hash_map.find(numToFind)!=hash_map.end()) { res.push_back(i); res.push_back(hash_map[numToFind]); return res; } else hash_map[nums[i]]=i; } return res; } };
python:
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ maps={} for i in range(len(nums)): if target-nums[i] in maps: return i,maps[target-nums[i]] else: maps[nums[i]]=i return -1,-1
标签:i++ order def and leetcode target div style 重复
原文地址:https://www.cnblogs.com/hotsnow/p/9524309.html