001两数之和

写在前面,参考的力扣官网的画解算法

hash映射

/*
 * @lc app=leetcode.cn id=1 lang=java
 *
 * [1] 两数之和
 */

// @lc code=start
class Solution {
    public int[] twoSum(int[] nums, int target) {
        
        //hash映射,创建集合对象,作为键的对象整数,值得对象存储整数
        //用接口Map引用对象会使程序更加灵活
        //key:nums[i];value:i
        Map<Integer,Integer>map =new HashMap<>();

        //遍历数组nums,i为当前下标
        for(int i=0;i<nums.length;i++){

            //每个值都判断map中是否存在target-nums[i]的key值
            if(map.containsKey(target-nums[i])){

                 //如果存在则找到了这两个值
                return new int[]{ map.get(target-nums[i]),i};
            }

            //如果不存在则将当前的(nums[i],i)存入map继续遍历
            map.put(nums[i],i);
        }

        //如果最后都没有结果,则抛出异常
        throw new IllegalArgumentException("No two sum solution");
    }
}
// @lc code=end

原文地址:https://www.cnblogs.com/lxr-xiaorong/p/13438541.html