# 题目描述

• `2 <= nums.length <= 103`
• `-109 <= nums[i] <= 109`
• `-109 <= target <= 109`
• 只会存在一个有效答案

# 朴素解法

``class Solution {public int[] twoSum(int[] nums, int t) {int n = nums.length;for (int i = 0; i < n - 1; i++) {for (int j = i + 1; j < n; j++) {if (t == nums[i] + nums[j]) return new int[]{i,j};}}return new int[]{};}``}``

# 哈希表解法

``class Solution {public int[] twoSum(int[] nums, int t) {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 a = nums[i], b = t - a;if (map.get(a) == i) map.remove(a);if (map.containsKey(b)) return new int[]{i, map.get(b)};}return new int[]{};}``}``

``class Solution {public int[] twoSum(int[] nums, int t) {Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {int a = nums[i], b = t - a;if (map.containsKey(b)) return new int[]{map.get(b), i};map.put(a, i);}return new int[]{};}``}``

1 声望

0 粉丝

0 条评论

# 题目描述

• `2 <= nums.length <= 103`
• `-109 <= nums[i] <= 109`
• `-109 <= target <= 109`
• 只会存在一个有效答案

# 朴素解法

``class Solution {public int[] twoSum(int[] nums, int t) {int n = nums.length;for (int i = 0; i < n - 1; i++) {for (int j = i + 1; j < n; j++) {if (t == nums[i] + nums[j]) return new int[]{i,j};}}return new int[]{};}``}``

# 哈希表解法

``class Solution {public int[] twoSum(int[] nums, int t) {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 a = nums[i], b = t - a;if (map.get(a) == i) map.remove(a);if (map.containsKey(b)) return new int[]{i, map.get(b)};}return new int[]{};}``}``

``class Solution {public int[] twoSum(int[] nums, int t) {Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {int a = nums[i], b = t - a;if (map.containsKey(b)) return new int[]{map.get(b), i};map.put(a, i);}return new int[]{};}``}``