1.题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
2.我的解答
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
for(int i=0;i
for(int j=i+1;j
if(nums[i]+nums[j]==target){
result[0]=i;
result[1]=j;
return result;
}
}
}
return result;
}
}
时间复杂度较高,时间复杂度为O(N^2)
3.优化
目的在于寻找数组中是否存在target-X
- 使用hashTable的ContainsKey(key)或者Contains(int key)都可以
public virtual bool Contains(object key)
{
return this.ContainsKey(key);
}
hashtable中含有这个key则返回true,没有则返回false
- 使用hashTable的get函数可以得到key对应的value值
hashTable<数组当前的值,对应的下标>
class Solution {
public int[] twoSum(int[] nums, int target)
{ Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
部分来自链接:leetcode-cn.com/problems/tw… 来源:力扣(LeetCode)