两数之和 java

1.使用HashMap

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums==null || nums.length==0){
            return new int[0];
        }
        //存储结果的数组
        int[] res = new int[2];
        //存储数组元素
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            int temp = target - nums[i];
            //如果包含该元素,就将这两个元素的下表存入数组
            if(map.containsKey(temp)){
                res[0] = i;
                res[1] = map.get(temp);
            }
            //如果当前两个数字不满足要求,就将第i个数存入数组
            map.put(nums[i],i);
        }
        return res;
    }
}

时间空间耗费较多

2.优化一下

class Solution{
    public int[] twoSum(int[] a,int target){
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<a.length;i++){
            if(map.containsKey(target-a[i])){
                return new int[] {map.get(target-a[i]),i};
            }
            map.put(a[i],i);
        }
        throw new IllegalArgumentException("no result");
    }
}

好一点点了

posted @   蹇爱黄  阅读(58)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示