# 题解

## 官方题解

### 1.暴力法

``````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[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}``````

• 时间复杂度：O(n^2)
• 空间复杂度：O(1)

### 2.两遍哈希表

``````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 i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}``````

• 时间复杂度：O(n)
• 空间复杂度：O(n)

### 3.一遍哈希表

``````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");
}``````

• 时间复杂度：O(n)
• 空间复杂度：O(n)

## 其他题解

### 1.耗时 1ms，内存 38MB

``````public int[] twoSum(int[] nums, int target) {
int indexArrayMax = 2047;
int[] indexArrays = new int[indexArrayMax + 1];
int diff = 0;
for (int i = 0; i < nums.length; i++) {
diff = target - nums[i];
if (indexArrays[diff & indexArrayMax] != 0) {
return new int[] { indexArrays[diff & indexArrayMax] - 1, i };
}
//等式左边的式子初始值为0
indexArrays[nums[i] & indexArrayMax] = i + 1;
}
throw new IllegalArgumentException("No two sum value");
}``````