leetcode链接: https://leetcode.cn/problems/two-sum/
解法:
1.暴力求解 双重循环 时间:o(n^2) 空间:o(1)
class Solution {
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[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return null;
}
}
2.hash表 时间:o(n^2) 空间:o(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> maps = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int gap = target - nums[i];
if(maps.containsKey(gap)){
return new int[]{i,maps.get(gap)};
}
maps.put(nums[i],i);
}
return null;
}
}