方法一:两次循环(o(n2))
class Solution {
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};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
方法二:用哈希表 (o(n))
哈希表的相关用法
创建哈希表 Map<Integer,Integer> hashMap = new HashMap<>();
哈希表键值对赋值 hashMap.put(a,b);
哈希表查找是否包括某个键 hashMap.containsKey(a);
哈希表获得某个键对应的值 hashMap.get(a);
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hashMap = new HashMap<>();
for(int i = 0;i<nums.length;i++)
{
hashMap.put(nums[i],i);
}
for(int i=0;i<nums.length;i++)
{
int containK = target - nums[i];
if(hashMap.containsKey(containK)&& hashMap.get(containK)!= i)
return new int []{i,hashMap.get(containK)};
}
throw new IllegalArgumentException("No two sum solution");
}
}
方法三,一遍哈希表
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}