# LeetCode算法题

```public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
res:
for (int i = 0;i < nums.length;i++) {
for (int j = i + 1;j < nums.length;j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
break res;
}
}
}
return result;
}

public static void main(String[] args) {
Solution solution = new Solution();
int[] a = {2,7,11,15};
int[] result = solution.twoSum(a,9);
for (int i = 0;i < result.length;i++) {
System.out.println(result[i]);
}
}
}```

0
1

```public class Solution1 {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>(nums.length);
for (int i = 0;i < nums.length;i++) {
int pre = target - nums[i];
Integer preIndex = map.get(pre);
if (preIndex != null) {
return new int[] {preIndex,i};
}
map.put(nums[i],i);
}
return null;
}

public static void main(String[] args) {
Solution1 solution = new Solution1();
int[] a = {2,7,11,15};
int[] result = solution.twoSum(a,9);
for (int i = 0;i < result.length;i++) {
System.out.println(result[i]);
}
}
}```

0
1