leetcode刷题日记——Two Sum
2015-12-20 16:05
323 查看
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
问题分析:题目的目标就是返回数组中的元素之和为目标元素的二个元素对应的下标。常规的解法就是采用双重循环的方式,时间复杂度为O(n*n),代码比较简单,实现如下:
但是,还可以进一步的优化,将时间复杂度降为O(n),采用一个map来保存,key用来保存值,value用来保存index,实现代码如下:
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
问题分析:题目的目标就是返回数组中的元素之和为目标元素的二个元素对应的下标。常规的解法就是采用双重循环的方式,时间复杂度为O(n*n),代码比较简单,实现如下:
public class Solution { public int[] twoSum(int[] nums, int target) { int[] indexs=new int[2]; int m=0,n=0; for(int i=0;i<nums.length-1;i++) for(int j=i+1;j<nums.length;j++){ if(nums[i]+nums[j]==target){ m=i+1; n=j+1; } } indexs[0]=m; indexs[1]=n; return indexs; } }
但是,还可以进一步的优化,将时间复杂度降为O(n),采用一个map来保存,key用来保存值,value用来保存index,实现代码如下:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> indexs; map<int,int> mapnums; for(int i=0;i<nums.size();i++){ mapnums[nums[i]]=i; } for(int i=0;i<nums.size();i++){ if(mapnums[target-nums[i]]) { indexs.push_back(i+1); indexs.push_back(mapnums[target-nums[i]]+1); return indexs; } } return indexs; } };
相关文章推荐
- HTML 5提供的一些新的标签用法以及和HTML 4的区别
- 向linux内核加入系统调用新老内核比較
- 《iOS Human Interface Guidelines》——Apple Pay
- $'\t' 解释
- 关于java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream解决办法
- ArcGIS 创建要素时提示“表已经被注册(table already registered)”
- 让正常网页呈现黑白色调的方法
- LBS的定位API
- Html5新标签解释及用法
- 安卓UI之安卓icon大小
- netfilter/iptables全攻略
- C#——重写与抽象类
- scala-39:ListBuffer、ArrayBuffer、Queue、Stack操作代码实战
- 2015年的我
- netfilter/iptables全攻略
- 防F12审查元素扒代码:按下F12关闭当前页面
- 数据结构小结(五) 数组与广义表
- linux => navicat for mysql 在ubuntu下的安装
- Object类 中的方法
- php中单引号与双引号的区别