class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap< >();
for(int i=0;i<nums.length;i++)
{
int minusgap = target-nums[i];
if(map.containsKey(minusgap))
{
return new int[]{map.get(minusgap),i};
}
map.put(nums[i],i);
}
throw new IllegalArgumentException("no two sum value!");
}
}
Solution 2:暴力遍历法
执行时间:58ms
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] index = new int[2];
int i,j=0;
for(i=0;i<nums.length;i++)
{
for(j=i+1;j<nums.length;j++)
{
if(nums[i]+nums[j]==target)
{
index[0]=i;
index[1]=j;
return index;
}
}
}
return index;
}
}