LeetCode/TwoSum Java

来源:互联网 发布:c 游戏编程 编辑:程序博客网 时间:2024/06/05 20:39

题目: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, and you may not use the same element twice.

题意:给个整数数组,返回两个数的索引如果如果这两个数相加等于一个指定的数,且不能使用同一个数两次,且输入将得到唯一的答案,即只会有一个结果。

思想:
1.采用Java中的HashMap遍历整个数组。
2.put(key,value):将数组放入HashMap中。
3.get(key):根据键得到相关的值。
4.注意:不能使用同一个元素两次!!!(如输入(3,3),如果不保证索引不相同,返回的值将为(0,0))。

这里写代码片package www.hugo.com;import java.util.HashMap;public class TwoSum {    public int[] twoSum(int a[],int target){        HashMap <Integer,Integer> map = new HashMap<Integer,Integer>();//创建一个HashMap        for(int i = 0;i < a.length;i++){            map.put(a[i],i);//将数组放入hashMap中,key=a[i] vaule=i;        int two[] = new int[2];//一个存储满足条件的两个数的索引的数组        for(int i = 0;i<a.length;i++){            if(map.containsKey(target-a[i])&&(map.get(target-a[i])!=i)){//Attention:1.map.containsKey(target-a[i]):表示判断是否hash表里面有一个值等于(target-a[i]),若有则返回true. 2.(map.get(target-a[i])!=i):表示判断是否是同一个数!!hash于上面put()是以值-索引的方式放入hashMap中的,由于get方法是通过键得到值,所以get得到的顺其自然是索引。                two[0] = i;                two[1] = map.get(target-a[i]);                break;            }        }        return two;    }}
0 0