[leetcode] 【数组】1. Two Sum
2016-05-22 02:16
393 查看
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].
方法a
简单做法就是遍历k遍,时间复杂度为O(n^k)。代码略。
方法b
如果要求返回的是数本身,则可以先排序,然后头尾夹逼。这一题不符,代码就不写了。
方法c
借助哈希表来标记,然后找差。
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].
题解
这是K sum题型的基础模型,题意就是在一个数组中找到和为target的所有的 【K个数组合】 。方法a
简单做法就是遍历k遍,时间复杂度为O(n^k)。代码略。
方法b
如果要求返回的是数本身,则可以先排序,然后头尾夹逼。这一题不符,代码就不写了。
方法c
借助哈希表来标记,然后找差。
//cpp class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res(2,0); map<int,int> flag; for(int i=0;i!=nums.size();i++) { int sub=target-nums[i]; if(flag.find(sub)!=flag.end()) { res[0]=flag[sub]; res[1]=i; return res; } flag[nums[i]]=i; } return res; } };
相关文章推荐
- 数据库的设计与维护
- STM32中断优先级--学习心得
- “广商百货”实现情况跟踪
- 在ie8上js实现简单的combobox功能(支持拼音检索)
- ubuntu use commandline download files
- Maven之(二)Maven生命周期
- 什么是「设计模式」?
- Maven之(二)Maven生命周期
- Maven之(一)Maven是什么
- Maven之(一)Maven是什么
- [OpenGL] OpenGL+VS2015环境配置
- Hibernate_HQL的各种查询_Demo
- 博客专用照片
- [leetcode] 【数组】128. Longest Consecutive Sequence
- nodejs+express+mongodb搭建网站
- 【Python】python 多线程两种实现方式
- 使用PHP开发一个简单的后台接口(响应移动端的get请求和post请求)
- iOS开发拓展篇—音效的播放
- 自定义轮播图,实现无限轮播、自动轮播、按下停止轮播
- [Android]WebView使用详解(一)——Native与JS相互调用(附JadX反编译)20160522