zoukankan      html  css  js  c++  java
  • 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
    
    
  • 相关阅读:
    [状压DP][二分]JZOJ 3521 道路覆盖
    字符串操作
    练习: 判断一个数是否为小数
    Python 深浅拷贝
    编码
    python中的 == 和 is 的区别
    Python3 字典的增删改查
    Python3 列表的基本操作
    初识 Python
    方法的入门
  • 原文地址:https://www.cnblogs.com/lxr-xiaorong/p/13438541.html
Copyright © 2011-2022 走看看