题解 | #两数之和#

两数之和

https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f

方法一:暴力破解法,使用两个for循环相加 看是否等于目标值,简单直观 便于理解。但是空间时间复杂度过高,部分用例超时没有通过。

    public int[] twoSum (int[] numbers, int target) {
        // write code here
         int[] res = new int[2];
        for (int i = 0; i < numbers.length; i++) {
            for (int j = i+1; j < numbers.length; j++) {
                if (i != j && numbers[i] + numbers[j] == target) {
                    res[0] = i+1;
                    res[1] = j+1;
                }
            }
        }
        return res;      
    }

方法二 hash表

具体做法:

使用Map来降低时间复杂度,遍历数组,如果没有 (target - 当前值) 就将当前数字存入哈希表,如果有,返回该数字下标即可。

    public int[] twoSum (int[] numbers, int target) {
        // write code here
      HashMap<Integer,Integer> hashMap = new HashMap();
        int[] res = new int[2];
        for (int i = 0; i < numbers.length; i++) {
            if (hashMap.containsKey(numbers[i])) {
                res[0] = hashMap.get(numbers[i]) + 1;
                res[1] = i + 1;
            } else {
                hashMap.put(target-numbers[i] ,i);
            }
        }
        return res;        
    }



#牛客网博客##牛客网##牛客网在线编程#
全部评论

相关推荐

这算盘打的
程序员小白条:都这样的,都是潜规则,你自己说可以实习一年就行了,实习可以随便跑路的
点赞 评论 收藏
分享
求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
炫哥_:哥们项目描述里面vector和mysql之类的都要写吗,直接开头技术栈巴拉巴拉就行了,完全不是技术点啊
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 14:00
不想多说了,什么逆天HR,还要教我礼貌😂
机械打工仔:这不纯傻卵吗,他还操心上别人老板了
投递BOSS直聘等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务