Leetcode(1)两数之和

题目:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

思路:
这里采用HashMap这种数据结构,将数组的元素值作为key,index作为value来建立map,这么做的原因是HashMap这种数据类型有通过key获取value的方法,但是没有直接通过value获取key的方法

    步骤:
            1、建立一个空的HashMap类型的数据表map
            2、对数组进行循环遍历,在每次遍历elem的时候,首先查看一下target-elem是否已经在map中
                    1)如果已经在了,则说明已经找到了,此时通过map的get方法查询到target-elem的索引值,并把它和当前的elem的索引值一起返回即可
                    2)如果不在map中,则将elem作为key,index所谓value存入到map中
            3、若2中的循环结束了,还没有找到,则抛出一个异常即可

    注意:这里需要对HashMap这种数据类型的常用方法比较熟悉,如果不熟悉可以通过查看JDK的API文档即可
import java.util.HashMap;
import java.util.Map;
class Solution {
    public int[] twoSum(int[] nums, int target)  {
     Map<Integer,Integer> map=new  HashMap<Integer,Integer>();
     for(int i=0;i<nums.length;i++)
     {
         int temp=target-nums[i];
         if(map.containsKey(temp))
         {
             return new int[]{map.get(temp),i};
         }
         map.put(nums[i],i);
     }
     throw new IllegalArgumentException("在数组nums中没有找到两个数,使得他们的和胃target");
    }
}

public class SolutionDemo {
    public static void main(String[] args) {
        Solution s=new Solution();
        int[] nums=new int[]{2,7,11,15};
        int target=9;
        int[] index=s.twoSum(nums, target);
        System.out.println("index =  ["+index[0]+", "+index[1]+"]");
    }
}

执行结果为:

index = [0, 1]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章