暴力破解
public 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;
}
}
哈希表
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> m = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (m.get(target - nums[i]) != null) {
return new int[]{m.get(target - nums[i]), i};
}
m.put(nums[i], i);
}
return new int[]{0, 0};
}
}
双指针也行
在这里插入代码片