Two Sum
2015-07-09 19:32
162 查看
题目: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)
解法:利用HashMap,存储数组中的值和Index,使用get方法,get到target-nums[i],
记录当前的index,否则将nums[i] put到HashMap中。时间复杂度只有O(n)。
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[] temp=new int[2]; for(int i=0;i<nums.length;i++){ for(int j=i+1;j<nums.length;j++){ if(nums[i]+nums[j]==target){ temp[0]=i+1; temp[1]=j+1; } } } return temp; } }
解法:利用HashMap,存储数组中的值和Index,使用get方法,get到target-nums[i],
记录当前的index,否则将nums[i] put到HashMap中。时间复杂度只有O(n)。
public class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //记录值和index int[] ret = new int[2]; //辅助数组 for(int i=0; i<nums.length; i++){ if(map.get(target-nums[i]) != null){ //找到值对应的index ret[0] = map.get(target-nums[i]) + 1; ret[1] = i+1; }else map.put(nums[i], i);//没有找到则记录 } return ret; } }
相关文章推荐
- 将字符串转化为数字的python实现
- [批处理教程之Shell]002.Linux 常用命令大全
- git实战(2)--本地初始化
- Linux的时间设置与同步(NTP)
- Oracle Partition 分区详细总结
- 悟 -- 如何做到高效产出,结合Linux 服务器开发的感悟
- POJ2492(A Bug's Life) && POJ1703(Find them, Catch them)带权(种类)并查集
- java String.subString用法
- Linux下samba的安装与配置
- opendaylight web service REST api
- ACM POJ 1328 Radar Installation
- java集合(上)
- N-Queens N皇后放置问题 回溯法
- 【SSH异常系列】The Struts dispatcher cannot be found.
- Allegro 16.5详细破解步骤
- POJ3167 Cow Patterns (KMP)
- KVC、KVO
- LeetCode169:Majority Element
- Ubuntu中Samba的安装配置和使用[图文]
- C8_指针