TwoSum

作者: Shiki | 来源:发表于2014-10-06 10:24 被阅读0次

Problem###

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


Analysis###

关键是寻找两个合适的数
最先以为序列式有序的,结果不是;
然后直接穷举所用组合,结果会超时;
最后使用HashMap来实现,key = 数的值,value = 数的位置:首先将所有的数与其位置存储于Map中,然后对于每个数去检测能和它组合成target的数的位置,如果没有,就下一个。


Tips###

1:numbers 是无序的!
2:穷举会超时!:
3:如果Hash搜索的时候是按numbers的顺序从前往后找的话,其本身就是index1小,index2大。


Implementation###

package twosum; import java.util.HashMap; public class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i = 0 ; i < numbers.length ; i++){ map.put(numbers[i], i); } for(int i = 0 ; i < numbers.length ; i++){ int left = target - numbers[i]; if(map.get(left) != null && map.get(left) != i){ int[] indexs = {(i+1),(map.get(left)+1)}; return indexs; } } return null; } }


相关文章

  • TwoSum

    题目大意: 找到数组中两个元素相加等于指定数的所有组合 情况一:给定数组中不含重复元素,且均为正整数 思路: 使用...

  • twoSum

    Problem Given an array of integers, return indices of the...

  • TwoSum

    刷题当然要从TwoSum开始了~~python刷题果然容易~~~class Solution(object):de...

  • TwoSum

    介绍:Two Sum给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。函数 twoSum 返回这两个相...

  • TwoSum

  • TwoSum

    Problem### Given an array of integers, find two numbers s...

  • TwoSum

    简单方法,两边循环,一个推着另一个,复杂度n2 使用map,检查过的存起来map,每拿到一个新的,就去map里查,...

  • TwoSum

    题目描述: Given an array of integers, return indices of the t...

  • twoSum

    给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。 你需要实现的函数twoSum需要返回这两个...

  • TwoSum

    暴力暴力算法时间复杂度O(n²),空间复杂度O(1) 两次遍历 HashMap时间复杂度:O(n),我们把包含有 ...

网友评论

      本文标题:TwoSum

      本文链接:https://www.haomeiwen.com/subject/dftptttx.html