【LeetCode解题】1#Two Sum

来源:互联网 发布:c语言闰年流程图 编辑:程序博客网 时间:2024/05/22 12:51

题目地址

题目描述

题目:Two Sum

描述:    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

分析:这是LeetCode上第一题,也就是开胃菜,大意是给定一个数组,和一个目标值,求出该数组中满足相加等于这个目标值的两个元素的下标,返回的是一个二元数组。题目保证结果存在且唯一。注意:一个元素不能重复使用。我们可以采用二重循环遍历数组的方式,直到找到符合条件的两个元素为止,但是时间复杂度是O(n^2),不推荐。由于同一个元素不能重复使用,因此利用Java集合中的HashMap即可轻松解决问题。既保证不重复,又可以在O(n)时间内完成遍历。先放代码

我的代码

public class Try {public int[] twoSum(int[] nums, int target) {HashMap<Integer,Integer> hm = new HashMap<>();int num = nums.length;for(int i = 0; i < num; i++) {if(hm.containsKey(nums[i])){int j = hm.get(nums[i]);return new int[]{j,i};}else {hm.put(target-nums[i], i);}}return new int[2];}        }

思路分析

       我们先定义一个HashMap为hm,Key是目标值与当前值的差,Value是下标。然后从头开始遍历,如果hm中有元素x的Key与当前遍历元素相等,即x.key = nums[i],由于hm中key存储的是之前遍历的数组元素被target减去后的到的数,即x.key = target - nums[j],所以target - nums[j] = nums[i],那么就得到了两个目标元素的下标,j和i 返回一个二元数组即可。如果hm中没有元素的Key与当前遍历元素值相等,说明(可以)与当前元素配对的值还没出现,那么就把target 与当前遍历元素的值相减,连同下标一起存入hm中,然后继续遍历。直到得出答案。