1.暴力
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=0;j<nums.length;j++){
while(i!=j){
if(nums[j]==target-nums[i])
return new int[]{i,j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
2.两遍哈希表
class Solution {
public int[] twoSum(int[] nums, int target) {
Map <Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
map.put(nums[i],i);
}
for(int j=0;j<nums.length;j++){
int kk=target-nums[j];
if(map.containsKey(kk)&&map.get(kk)!=j)
return new int[]{j,map.get(kk)};
}
throw new IllegalArgumentException("No two sum solution");
}
}