链接:https://leetcode-cn.com/problems/two-sum/submissions/
java题解(hashmap)
时间复杂度:o(n)
空间复杂度:o(n)
import java.util.HashMap;
class Solution {
public static void main(String[] args) {
Solution s = new Solution();
int[] nums = {};
int target = 17;
int[] res = s.twoSum(nums, target);
for(int num : res) {
System.out.print(num + " ");
}
}
public int[] twoSum(int[] nums, int target) {
if(nums == null || nums.length < 2)
return new int[0];
HashMap<Integer, Integer> map = new HashMap<>();
int value = -1;
for(int i = 0; i < nums.length; i++) {
value = target - nums[i];
if(map.containsKey(value)) {
return new int[]{map.get(value), i};
}
map.put(nums[i], i);
}
//throw new IllegalArgumentException("No two sum solution");
return new int[0];
}
}