領釦演算法:1 兩數之和
阿新 • • 發佈:2018-11-21
給定一個整數陣列 nums
和一個目標值 target
,請你在該陣列中找出和為目標值的 兩個 整數。
你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個陣列中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9 因為 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
輸入的引數: public int[] twoSum(int[] nums, int target)
解決步驟:
1.用一個HashMap儲存陣列中的資料,[Integer,Integer] 中key為陣列的值,value為陣列的下標。
2.遍歷給定的陣列,得到target和本次遍歷數值的差comp,判斷comp是否在HashMap集合中,且不是本身。返回本次數值的下標 i 和 map.get(comp)。
程式碼:
public class TwoSum { public static void main(String[] args) { int nums[] = {7,3,4,5,2}; int target = 9; int[] rs = twoSum(nums, target); for (Integer ele : rs) { System.out.println(ele); } } public static int[] twoSum(int[] nums, int target){ HashMap<Integer,Integer> map = new HashMap(); for (int i = 0;i<nums.length ; i++){ map.put(nums[i],i); } for (int j = 0;j<nums.length ; j++){ int temp = target - nums[j]; if(map.containsKey(temp)&&map.get(temp)!=j){ return new int[]{j,map.get(temp)}; } } return null; } }
執行截圖: