题目
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].
方法1
暴力索引,时间复杂度为O(n^2)。
public class TwoSum {
/**
* 时间复杂度为O(n^2)
* @param nums
* @param target
* @return
*/
public static int []twoSum1(int []nums,int target){
int index1,index2;
int []index = new int[]{0,1};
for(int i = 0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(target ==(nums[i]+nums[j])){
index[0]=i;
index[1]=j;
return index;
}
}
}
return index;
}
方法2
使用HashMap来做,首先检验target-nums[i]能否加入到HashMap中,若能,则说明前面的数据没有与第i个字符的组合,当添加不成功,则说明存在符合的组合,记录索引,时间复杂度为O(n)。时间缩短很多
public static int []twoSum2(int []nums,int target){
int []index = new int[]{0,1};
HashMap<Integer, Integer> hm = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(hm.containsKey(target-nums[i])){
index[1] = i;
index[0] = hm.get(target-nums[i]);
return index;
}else {
hm.put(nums[i], i);
}
}
return index;
}