首先来看题意:
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:暴力解法
暴力解法的具体思路是:遍历数组中两个元素的所有组合的可能,然后计算出每种组合相加的值与目标值进行比较,如果与目标值相等的话,则返回该组合的下标。具体代码如下:
public int[] twoSum(int[] nums,int target) {
for(int i=0;i<nums.length;i++) {
for(int j=i+1;j<nums.length;j++) {
if(nums[i]+nums[j]==target)
return new int[] {i,j};
}
}
}
通过上述代码可以看到该方法的时间复杂度比较高,如果数组的长度为N,那么时间复杂度为:O(N2)
思路2:利用Java集合
该方法的思路是:首先把数组中的元素和元素对应的下标以key-value 的形式保存在集合Map 中。然后利用目标值target 减去数组中的某个元素nums[i] 得到一个差值,然后遍历集合Map 中是否有该差值,若有则返回下标i 以及差值的下标。具体代码如下:
public int[] twoSum(int[] nums,int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++) {
int res=target-nums[i];
if(map.containsKey(res)&&map.get(res)!=i)
return new int[] {i,map.get(res)};
map.put(nums[i],i);
}
}
假设数组的长度为N,由于用到了集合,因此该方法的空间复杂度为O(N),时间复杂度为O(N)
扩展:思路2利用了Java集合中的Map 中的键的唯一性来寻找对应的数组下标。利用这种特性还可以用来统计数组中元素的相对应的数量等等。