[LeetCode刷題菜鳥集] 1.Two Sum 兩數之和
阿新 • • 發佈:2018-11-10
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].
Time Limit Exceeded,這個演算法的時間複雜度是O(n^2)
思路:可以事先將其儲存起來,使用一個HashMap,來建立數字和其座標位置之間的對映,我們都知道HashMap是常數級的查詢效率,這樣,我們在遍歷陣列的時候,用target減去遍歷到的數字,就是另一個需要的數字了,直接在HashMap中查詢其是否存在即可,注意要判斷查詢到的數字不是第一個數字,比如target是4,遍歷到了一個2,那麼另外一個2不能是之前那個2,整個實現步驟為:先遍歷一遍陣列,建立HashMap對映,然後再遍歷一遍,開始查詢,找到則記錄index。
原始碼:
public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); int[] res = new int[2]; for (int i = 0; i < nums.length; ++i) { m.put(nums[i], i); } for (int i = 0; i < nums.length; ++i) { int t = target - nums[i]; if (m.containsKey(t) && m.get(t) != i) { res[0] = i; res[1] = m.get(t); break; } } return res; } }
改進程式碼:
//解決缺陷:若陣列中有多組兩數之和 public static List<int[]> twoSum(int[] nums, int target) { HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); List<int[]> list=new ArrayList<int[]>(); for (int i = 0; i < nums.length; ++i) { m.put(nums[i], i); } for (int i = 0; i < nums.length; ++i) { int[] tmp = new int[2]; int t = target - nums[i]; //fix:!=改成>,避免重複 if (m.containsKey(t) && m.get(t) > i) { tmp[0] = i; tmp[1] = m.get(t); list.add(tmp);//fix:nums中有多組符合條件 } } //解決缺陷:若陣列中有多組兩數之和 for(int i=0;i<list.size();i++){ System.out.println("list:"+list.size()+"--"+list.get(i)[0]+"And"+list.get(i)[1]); } return list; }