问题描述:
给定一个整数数组和一个目标数字,如果数组中的两个数字之和等于目标数字,则输出这两个数字的下标索引值。
示例:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
输入和输出:
输入:int nums[ [2, 7, 11, 15]],int target=9
输出:int result[0,1]
//===========================================================================
思路1:
当然首推最容易找到最笨的办法是暴力查找:两层循环遍历数组,如果两数之和等于目标数字,记录下标i和j。时间复杂度O(n2)。
//*************************************************************
//File Name: twosum.java
//Author: bingbing
//Mail: 2015262642@mail.nwpu.edu.cncom
//Created Time: 2016年04月16日 星期五
//*************************************************************
public int[] twoSum(int[] nums, int target) {
int []temp = new int[2];//临时变量,存储两个数字的索引值
for(int i = 0;i<nums.length;i++){
for(int j =i+1;j<nums.length;j++){
if(nums[i]+nums[j] ==target){//如果为真,答案找到
temp[0] = i;
temp[1] = j;
}
}
}
return temp;
}
运行结果:
leetcode的运行结果是通过,但是时间复杂度太高,除非没有更好的办法,不是一段优雅的代码。
//===========================================================================
思路2:使用数据结构中的hashMap会大大地降低时间复杂度:
1.创建hashMap对象,
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
//hashMap<key,value>,这里的key是数组里面的数字,value是数字对应索引下标值。
2.遍历数组,在第i中时,如果key=table.get(target-num[i])为空,则加入table.put(num[i],i);,反之,则找到答案:输出i和key即为所求。
//*************************************************************
// File Name: twosum.java 改进hashMap的做法
// Author: bingbing
// Mail: 2015262642@mail.nwpu.edu.cncom
// Created Time: 2016年04月16日 星期五
//*************************************************************
public int[] twoSum(int[] nums, int target) {
Integer key = 0;
int []answer = new int[2];
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
for(int i = 0;i<nums.length;i++){
key = table.get(target-nums[i]);
if (key == null) table.put(nums[i], i);
else {
answer[1]=i;
answer[0]=key;
}
}
return answer;
}
运行结果:
这个结果是非常不错的了,比暴力破解的效率至少高于数十倍。这也是兵兵想到的最好的思路了。下面我说下自己的理解:
这个算法只用了O(n)的hashmap时间复杂度,思路是循环一次,
每次都判断当前数组索引位置的值在不在hashtable里,不在的话,加入进去,key为数值,value为它的索引值;在的话,取得他的key,记为n(此时n一定小于循环变量i),
接下来再在hashtable中查找(target-当前数值)这个数,利用了hashtable中查找元素时间为常数的优势(直接映射,先找value的hashCode,在通过hashCode找到value的存储位置),如果找到了就结束。
//===========================================
本文探讨了在给定数组中寻找两个数之和等于目标值的问题,提出了两种解决方案:暴力搜索与哈希表方法。暴力搜索通过双重循环实现,但时间复杂度较高。哈希表方法则显著提升了效率,仅需O(n)的时间复杂度即可解决问题。
527

被折叠的 条评论
为什么被折叠?



