垃圾刷题day1
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++){
int sum = 0;
sum = nums[i] + nums[j];
if(target == sum) {
return new int[] {i,j};
}
}
}
return null;
}
}
方法2 哈希
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0;i < nums.length;i++){
int minus = target - nums[i];
if(map.containsKey(minus)) {
return new int[] {map.get(minus),i};
}
map.put(nums[i],i);
}
return null;
}
}