题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路:
这道题如果采用暴力的方法来解决的话,就是通过两个for循环来遍历给定的数组。这样的做比较费时。比较好的方式是采用HashMap的方式来解决该问题。通过HashMap来存储数组中的数组和对应的下标。最后通过两次调用HashMap即可获得两个元素的下标。
import java.util.HashMap;
/*
* @author: mario
* @date: 2019/1/4
* 两个数之和
* **/
public class Problem01 {
public int[] twoSum(int[] nums, int target){
if(nums.length == 0){
return nums;
}
int[] result = new int[2];
HashMap<Integer, Integer> hash = new HashMap<>();
for(int i = 0; i < nums.length; i++){
hash.put(nums[i], i);
}
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if(hash.containsKey(temp) && hash.get(temp) != i){
result[0] = i;
result[1] = hash.get(temp);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums = {2,7,11,15};
Problem01 pb = new Problem01();
int[] result = new int[2];
result = pb.twoSum(nums, 9);
System.out.println("result:"+result[0]);
System.out.println("result:"+result[1]);
}
}
leetcode题目地址: https://leetcode-cn.com/problems/two-sum/
网友评论