
原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2ba4i/
解法一:
public static int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if ( i==j ){
continue;
}
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
思路:冒泡排序,双循环,计算不同下标的值的和与目标值是否一样,一样返回这两个数的下标即可
2025-10-28 start:
解法二:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] re = new int[2];
Map<Integer,Integer> map = new HashMap();
for (int i = 0 ; i < nums.length; i++) {
int value = nums[i];
if (map.get(target - value) != null) {
re[0] = map.get(target - value);
re[1] = i;
return re;
}
map.put(value,i);
}
return re;
}
}
思路: hash表,key存数组元素的值,value存数组的下标,循环时如果target -value为key的map不为null,就表示当前的下标和map中存的value就是我们要的下标值。
end