1.题目描述
LeetCode链接: link.
2.我的答案
暴力获取的方法
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result =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){
result[0]=i;
result[1]=j;
return result;
}
}
}
return null;
}
}
3.参考答案
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indexs = new int[2];
// 建立k-v ,一一对应的哈希表
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
if(hash.containsKey(nums[i])){
indexs[0] = i;
indexs[1] = hash.get(nums[i]);
return indexs;
}
// 将数据存入 key为补数 ,value为下标
hash.put(target-nums[i],i);
}
// // 双重循环 循环极限为(n^2-n)/2
// for(int i = 0; i < nums.length; i++){
// for(int j = nums.length - 1; j > i; j --){
// if(nums[i]+nums[j] == target){
// indexs[0] = i;
// indexs[1] = j;
// return indexs;
// }
// }
// }
return indexs;
}
}
分析: 时间复杂度为O(n)
(1)建立一个hash表,将数组数据存入其中,其中key为补数,value为下标。
(2)遍历数组,当hash表中存在对应target-num[i]的值,则返回两者下标