public class TwoSum {
public static int[] twoSum(int[] nums, int target) {
//定義一個res數組用于記錄兩個數的下标并傳回;
int[] res = new int[2];
//定義一個Hashmap,周遊數組後存放其中,其中key為數組中元素的值;value為其對應的下标;
HashMap<Integer,Integer> map = new HashMap<>();
//周遊數組,将資料添加到hashmap中;
for(int i=0; i<nums.length; i++) {
map.put(nums[i], i);
}
//周遊數組,用target-nums[i]得到差;
for(int i=0; i<nums.length;i++) {
int t = target - nums[i];
//判斷這個差是否在hashmap中,也就是另一個待找出的數;
if (map.containsKey(t) && map.get(t) != i) {
res[0] = i;
res[1] = map.get(t);
break;
}
}
//傳回結果;
return res;
}