一、题目名称java
Two Sum(两个数的和)数组
二、题目地址code
https://leetcode.com/problems/two-sum/ci
三、题目内容leetcode
Given an array of integers, return indices of the two numbers such that they add up to a specific target.get
You may assume that each input would have exactly one solution.input
Example:
io
Given nums = [2, 7, 11, 15], target = 9, Because nums[] + nums[] = 2 + 7 = 9, return [0, 1].
题目大体意思:给定一个整型数组,返回它的其中两个元素的下标,使得这两个元素的和等于目标元素的值class
你能假设每一个输入都能获得精确的结果。循环
四、题目分析
首先,题目是在数组中找两个元素的和等于目标元素,返回的倒是两个元素的下标;从而能够想到使用Map集合,由于map集合存储数据是键值对的形式,即map集合的键存储找到的元素,值存储找到的元素的下标。
主要思路是:遍历数组获得数组中的每个元素,再判断集合中是否包含该元素的键,
若是不包含:将目标元素减去该元素的差做为键,该元素的下标做为值存到集合中。
若是包含:在集合中找到这个元素做为键所对应的值,并将这个值存到新建立的数组中做为第一个元素。
而后将这个元素的下标做为第二个原素存到新建的数组中。
而后break跳出循环。
主要代码以下:
public int[] twoSum(int[] nums, int target) { int[]result = new int[2]; HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ if(hm.containsKey(nums[i])){ result[0] = hm.get(nums[i]); result[1] = i; break; }else{ hm.put(target-nums[i],i); } } return result; }