leetcode
Posted 热之雪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode相关的知识,希望对你有一定的参考价值。
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
以上是关于leetcode的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode810. 黑板异或游戏/455. 分发饼干/剑指Offer 53 - I. 在排序数组中查找数字 I/53 - II. 0~n-1中缺失的数字/54. 二叉搜索树的第k大节点(代码片段