小二終于開通博客了,真是高興。最近在看Java,所以就拿leetcode練練手了。以后我會將自己解體過程中的思路寫下來,分享給大家,其中有我自己原創的部分,也有參考別人的代碼加入自己理解的部分,希望大家看了多提意見,一塊加油。
問題描述:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2
解體思路:
設立一個HashMap,其中鍵值key為數組中數值,對應值value則為該數組下標值。
從數組最開始往后遍歷,每次求出該值對應target-numbers[i]的值在HashMap中是否存在。如果該值已經存在,那么則找到兩個值的和為target值,返回即可;如果該值不存在,則把(numbers[i], i)放入HashMap中。
整個算法的時間復雜度為O(n)。
代碼如下:
import java.util.*;public class Solution { public int[] twoSum(int[] numbers, int target) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(numbers.length * 2); int[] results = new int[2]; for(int i = 0; i < numbers.length; i++){ Integer temp1 = map.get(target - numbers[i]); if(temp1 == null){ map.put(numbers[i], i); } else{ results[0] = i + 1; results[1] = temp1 + 1; if(results[0] > results[1]){ int temp2 = results[0]; results[0] = results[1]; results[1] = temp2; } return results; } } return null; }}新聞熱點
疑難解答