LeetCode------Two Sum
2015-07-06 13:06
337 查看
●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
●中文简要的意思是:给你一个整数的数组,和一个目标值,在数组中找到两个数字,使得这两个数字的加和等于目标值,输出这两个数字的位置坐标。
●解决这个问题的方法有很多,我最先想到的是试探法,即双层的循环,找到合适的就输出,代码如下:
结果通过:Accepted
●还有另外一种方法,利用HashTable的存贮和查找元素的特性来解决这个问题,代码上只用了一层的循环,但其实资源的消耗上应该或高于第一种方式,因为用了集合数组,必不可少的增加了资源的消耗,且HashTable查找元素的操作底层也肯定是便利了全部的数组元素。
二者的效率上都不是很理想,希望读者有更好的解决方案。
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
●中文简要的意思是:给你一个整数的数组,和一个目标值,在数组中找到两个数字,使得这两个数字的加和等于目标值,输出这两个数字的位置坐标。
●解决这个问题的方法有很多,我最先想到的是试探法,即双层的循环,找到合适的就输出,代码如下:
public int[] twoSum(int[] nums, int target) { int[] reslut = new int[2]; //试探法解决TwoSum for(int i=0;i<nums.length;i++){ for(int j=i+1;j<nums.length;j++){ if(nums[i]+nums[j]==target){ reslut[0]=i+1; reslut[1]=j+1; return reslut; } } } return reslut; }
结果通过:Accepted
●还有另外一种方法,利用HashTable的存贮和查找元素的特性来解决这个问题,代码上只用了一层的循环,但其实资源的消耗上应该或高于第一种方式,因为用了集合数组,必不可少的增加了资源的消耗,且HashTable查找元素的操作底层也肯定是便利了全部的数组元素。
public int[] twoSum(int[] nums, int target) { int[] reslut = new int[2]; Hashtable<Integer,Integer> list=new Hashtable<Integer,Integer>(); for(int i=0;i<nums.length;i++){ Integer n=list.get(nums[i]); if(n==null){ list.put(nums[i],i); } n=list.get(target-nums[i]); if(n!=null){ reslut[0]=i+1; reslut[1]=n+1; return reslut; } } return reslut; }
二者的效率上都不是很理想,希望读者有更好的解决方案。
相关文章推荐
- TCP/IP协议详解v1(第一章概述)
- 文章标题
- k-means算法MATLAB和opencv代码
- android studio 错误集合
- EasyUI Datagrid IE浏览器中滚动条不起作用
- spring xml properties split with comma for list
- 教你如何下载音乐的网站只试镜
- GRE写作必备句型
- 《JAVA程序设计》实训第四天——《猜猜看》游戏
- List,Set,Map用法以及区别
- Accessing SQL Server Database in Editable GridView
- 金朝阳——软件测试试题11道题目分享
- 【网络互联技术】(三) 网络互联基础。
- Spring学习(6)---Bean定义及作用域的例子
- mdeditor
- 【网络互联技术】(三) 网络互联基础。
- 别再用高考来绑架孩子们心中的“公平”
- FireDAC DataSnap
- 五种利用strace查故障的简单方法
- Ubuntu无法启动只有光标闪烁解决方案