首页 > 其他 > 详细

LeetCode 1

时间:2020-06-17 00:35:30      阅读:77      评论:0      收藏:0      [点我收藏+]

1. 两数之和

本题可以有两种方法,一种先排序,再用双指针法找到两数。另一种利用哈希表存储值对应的下标,如果在表中找到target-nums[i]对应的值,则直接输出

Java

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> hash = new HashMap<>();
        for(int i = 0 ; i < nums.length ; i++){
            if(hash.containsKey(target-nums[i])){
                return new int[]{hash.get(target-nums[i]),i};
            }
            hash.put(nums[i],i);
        }
        return null;
        
    }
}

LeetCode 1

原文:https://www.cnblogs.com/xkf97/p/13149932.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!