版权声明:版权声明:本文为博主原创文章,博客地址:https://blog.csdn.net/imbingoer 未经博主允许不得转载 https://blog.csdn.net/imbingoer/article/details/85232361
题目
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
翻译
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
思路分析
- 暴力法。双重for循环,效率低O(N^2)
- 使用HashMap【线程不安全】或者是hashTable[使用sychronized,线程安全]。底层实现是entry数组+单链表。自带containkey和containValue。
代码
下面这段代码可以精简,不过这样的思路更清晰些。更有所爱,两个算法的效率都是O(n),后者相比更优秀些。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
Map<Integer,Integer> map = new HashMap<>();
for (int i=0;i<nums.length;i++){
map.put(nums[i],i );
}
//搜索
for (int j=0;j<nums.length;j++){
if (map.containsKey(target-nums[j])){
result[0]=j;
result[1]=map.get(target-nums[j]);
if (result[0]!=result[1]){
break;
}
}
}
return result;
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
Map<Integer,Integer> map = new HashMap<>();
for (int i=0;i<nums.length;i++){
//每一次把数放入map之前先检查map中是否已经存在和当前数配对的另外一个数
if (map.containsKey(target-nums[i])){
result[0]=map.get(target-nums[i]);
result[1]=i;
}
map.put(nums[i],i );
}
return result;
}
}