码迷,mamicode.com
首页 > 其他好文 > 详细

两数之和

时间:2019-10-13 01:01:06      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:坐标   public   targe   取出   get   使用   相加   for   获取   

利用哈希算法可以在O(1)的复杂度内找到目标元素,减少问题查询消耗的时间。

一、题目

??给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。(假设每种输入只会对应一个答案。但是,不能重复利用这个数组中同样的元素)

解法一:使用暴力解法,用双重循环遍历,外层遍历每个元素,内层遍历从外层下标之后的所有元素,若两个元素相加结果为target,则两个下标即所求结果。

public int[] twoSum(int[] nums, int target) {
    int[] result = new int[2];
    for (int i = 0; i < nums.length; i ++) {
        for (int j = i + 1; j < nums.length; j ++) {
            if (nums[i] + nums[j] == target) {
                result[0] = i;
                result[1] = j;
                break;
            }
        }
    }
    return result;
}

解法二:利用哈希存放元素值以及其下标,对数组做一次遍历,如果与当前元素相加为target的另一个加数在哈希表中,则取出元素及坐标,获取结果。如果不在,则把当前元素以及其下标加入哈希表。最后只要存在结果,遍历元素时在哈希表会存在一个元素使得两者之和为target。

public int[] twoSum(int[] nums, int target) {
    int[] result = new int[2];
    HashMap<Integer, Integer> hashMap = new HashMap<>();
    int temp;

    for (int i = 0; i < nums.length; i ++) {
        temp = target - nums[i];
        if (hashMap.get(temp) != null) {
            result[0] = hashMap.get(temp);
            result[1] = i;
            break;
        }
        hashMap.put(nums[i], i);
    }
    return result;
}

两数之和

标签:坐标   public   targe   取出   get   使用   相加   for   获取   

原文地址:https://www.cnblogs.com/idempotent/p/11664257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!