package com.javayihao.arithmetic.test; import java.util.HashMap; import java.util.Map; /** * 題意描述: * Given an array of integers, return indices of the two numbers such that they add up to a specific target. * You may assume that each input would have exactly one solution, and you may not use the same element twice. * Example: * Given nums = [2, 7, 11, 15], target = 9, * Because nums[0] + nums[1] = 2 + 7 = 9, * return [0, 1]. * 解題思路: * 給定一個數組和一個目標值,求出數組中兩數相加等於目標值,返回兩數的下標,很容易想到遍歷,直接使用使用兩層for循環 * ,但是這種暴力遍歷方法的時間複雜O(n^2),是一種低效的算法, * 們可以事先將其存儲起來,使用一個HashMap,來建立數字和其座標位置之間的映射,我們都知道HashMap是常數級的查找效率,這樣, * 我們在遍歷數組的時候,用target減去遍歷到的數字,就是另一個需要的數字了,直接在HashMap中查找其是否存在即可,注意要判斷查找到的數字不是第一個數字, * 比如target是4,遍歷到了一個2,那麼另外一個2不能是之前那個2,整個實現步驟爲:先遍歷一遍數組,建立HashMap映射,然後再遍歷一遍,開始查找,找到則記錄index。代碼如下: * */ public class TwoSum { public static void main(String[] args) { int arr[] = {2,5,7,3,9}; int[] index = getIndex(arr,12); for (int i = 0; i < index.length; i++) { System.out.println(index[i]); } } public static int[] getIndex(int[] arr,int target){ Map<Integer,Integer> map = new HashMap<>(); int[] result = new int[2]; for (int i = 0; i < arr.length; i++) { if(map.containsKey(target-arr[i])){//判斷map集合中有沒有要找的值 result[0]=map.get(target-arr[i]); result[1]=i; break; } map.put(arr[i],i); } return result; } }
算法和數據結構內功修煉之[LeetCode] Two Sum 兩數之和
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.