LeetCode/TwoSum Java

题目: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值