记一个简单笔记
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
方法一:暴力破解
public int[] twoSum(int[] nums, int target) {
int i;
int j;
int count_i = 0;
int count_j = 0;
int[] num = new int[2];
for(i=0;i<nums.length;i++){
for(j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
count_i = i;
count_j = j;
}
}
}
return new int[]{count_i,count_j};
}
方法二:哈希遍历*2
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) { //建立哈希K-V表,因为求数组下标,所以数组下标为v,数组值为k
hashMap.put(nums[i],i);
}
int temp = 0; //存储target - nums[i]
//开始核心代码
for (int i = 0; i < nums.length; i++) {
temp = target- nums[i];
if(hashMap.containsKey(temp)&&hashMap.get(temp)!=i){ //hashMap.get(temp)!=i 解决target=6,nums=[3,3],防止key把校验时把自己纳入其中
return new int[]{i,hashMap.get(temp)};
}
}
return null;
}
方法三:哈希遍历*1
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if(hashMap.containsKey(target-nums[i])){ //每查询一次,弱不符合,可查询条目多一条
return new int[]{i,hashMap.get(target-nums[i])};
}
hashMap.put(nums[i],i);
}
return null;
}