leetcode刷题笔记

栏目: 编程工具 · 发布时间: 6年前

内容简介:妙解法:首先遍历一次整数数组,将数组下标和值建立哈希表,再从头遍历一次哈希表,先得出当前读取的位置

问题:

给定一个整数数组 nums 和一个目标值 target

,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

妙解法:

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    //建立hashmap
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    //在哈希表中遍历每个元素,找到可能与之匹配成target的下标
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsValues(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

解释

首先遍历一次整数数组,将数组下标和值建立哈希表,再从头遍历一次哈希表,先得出当前读取的位置 i 上对于 target 的差 complement ,得到后通过查看该值是否保存在哈希表的value中,若存在,返回该值的 key ,否则读取下一元素。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

A Common-Sense Guide to Data Structures and Algorithms

A Common-Sense Guide to Data Structures and Algorithms

Jay Wengrow / Pragmatic Bookshelf / 2017-8-13 / USD 45.95

If you last saw algorithms in a university course or at a job interview, you’re missing out on what they can do for your code. Learn different sorting and searching techniques, and when to use each. F......一起来看看 《A Common-Sense Guide to Data Structures and Algorithms》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具