一、leetcode算法
1、两数之和
1.1、题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
1.2、思路
这里最简单的是可以用双层for循环来解决问题,但是双层for循环的时间复杂度为n^2,所以这样解决时间复杂度太高,这时我们可以将数据放入一个map中来解决复杂度高的问题。.
1.3、答案
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer,Integer> hashmap = new HashMap<Integer,Integer>(); for(int i = 0; i < nums.length; i++){ if(hashmap.containsKey(nums[i])){ return new int[]{hashmap.get(nums[i]), i}; } hashmap.put(target - nums[i], i); } return null; } }