Two Sum
来源:互联网 发布:h5小游戏源码 编辑:程序博客网 时间:2024/06/16 20:00
Difficulty:Easy
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].
MySolution: O(n²)
vector<int> twoSum(vector<int>& nums, int target) { vector<int> a(2); //※函数返回类型是vector<int>,所以需要定义此类型变量 //nums.size()和sizeof(nums)返回的值是不同的 for(int i = 0; i<nums.size(); i++) { for(int j = 0; j<nums.size(); j++) { if((i != j) && (nums[i]+nums[j] == target)) { a[0] = i; a[1] = j; break; } } } return a; }
OtherSolutions:O(n)
vector<int> twoSum(vector<int> &numbers, int target){ //Key is the number and value is its index in the vector.unordered_map<int, int> hash;vector<int> result;for (int i = 0; i < numbers.size(); i++) {int numberToFind = target - numbers[i];//遍历vector,计算出每个值跟目标值的差值,再用hash函数查找差值 //if numberToFind is found in map, return themif (hash.find(numberToFind) != hash.end()) {result.push_back(hash[numberToFind]);//将符合条件的数据在vector中的位置存到result中并返回resultresult.push_back(i);return result;} //number was not found. Put it in the map.hash[numbers[i]] = i;//将vector中的值作为map的键,对应的index作为map的值,在循环中,比较并查找符合条件的值得同时,在map中添加键值对,这种方法需要两个值都在map中}return result;}
public class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>(); for(int i = 0; i < numbers.length; i++){ Integer diff = (Integer)(target - numbers[i]); if(hash.containsKey(diff)){ int toReturn[] = {hash.get(diff)+1, i+1}; //在LeetCode提交时候不+1才能通过 return toReturn; } hash.put(numbers[i], i); } return null; }}
class Solution(object): def twoSum(self, nums, target): if len(nums) <= 1: return False buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i]//buff_dict[nums[i]]返回的是target - nums[i]的位置j,i为nums[i]的位置i else: buff_dict[target - nums[i]] = i//字典里存键值对,nums[i]与target的差值为字典的键,nums[i]在nums中的位置i为值,这种方法不用把nums[i]和对应的target-nums[i]全存进字典
Extended:
C++ unordered_map
map/unordered_map原理和使用整理
阅读全文
0 0
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Java学习笔记—时间和日期
- 希腊字母查询
- 设计模式——观察者模式
- Oracle 12c 多租户专题|12cR2中PDB内存资源管理
- 序列容器
- Two Sum
- 系统分区
- 使用srvany.exe将任何程序作为Windows服务运行
- spring boot 使用注解@async实现异步调用
- Linux Socket编程(转载)
- Macbook编译安装SAGA
- jQuery--checkbox全选/取消全选
- 数据结构之顺序存储
- 序列容器之Deque