給定一個整數數組 nums
和一個目標值 target
,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。git
你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。github
示例:數組
給定 nums = [2, 7, 11, 15], target = 9 由於 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]
我首先想到的也是暴力解決的辦法,出現了兩次問題,1.沒有設置默認值,2.第二個for循環的length-1了code
/** * @Author : Yanqiang * @Date : 2019/5/24 * @Param : [nums, target] * @return : int[] * @Description : 兩數之和, ---暴力運算 */ public static int[] twoSum1(int[] nums, int target) { //定義默認返回值 int[] result = {0,0}; for (int i = 0; i<nums.length; i++){ //目標值a = 兩數之和 - 當前值 int a = target - nums[i]; //從當前值日後循環,好比{2, 7, 11, 15};i爲2,就從7開始查 for (int k = i+1; k<nums.length; k++){ //若是nums[k] = 目標值a,說明找到了 if (nums[k] == a){ result[0] = i; result[1] = k; } } } return result; } /** * @Author : Yanqiang * @Date : 2019/5/24 * @Param : [nums, target] * @return : int[] * @Description : 兩數之和, ---HashMap匹配 */ public static int[] twoSum2(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { //目標值a = 兩數之和 - 當前值 int a = target - nums[i]; //若是HashMap包含目標值 a=nums[i] ,說明找到了 if (map.containsKey(a)) { return new int[] { map.get(a), i }; } //若是沒有重複的,HashMap存放的是Map<當前值, 當前值的數組下標> map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); }
public static void main(String[] args) { //int[] nums = {3,2,4}; int[] nums = {2, 7, 11, 15}; System.out.println(Arrays.toString(twoSum2(nums, 9))); }
LeetCode 所有解答題目,可移步 GitHub:https://github.com/yan-qiang/LeetCodeip