1. 程式人生 > >twoSum 必須要返回能夠相加等於目標數字的兩個數的索引,且index1必須要小於index2。

twoSum 必須要返回能夠相加等於目標數字的兩個數的索引,且index1必須要小於index2。

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [1, 2].
import java.util.HashMap;

/**
 * 要求:這個函式twoSum必須要返回能夠相加等於目標數字的兩個數的索引,且index1必須要小於index2。
 * 請注意一點,你返回的結果(包括index1和index2)都不是基於0開始的。你可以假設每一個輸入肯定只有一個結果。
 * 
 * @author pomay
 *
 */
public class TwoSum {
	// 時間複雜度o(n)
	public int[] sum(int[] numbers, int target) {
		int[] result = new int[numbers.length];
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		// 因為題目要求返回的結果(包括index1和index2)都不是基於0開始的,將值和index存入map
		for (int i = 0; i < numbers.length; i++)
			map.put(numbers[i], i + 1);
		// 從第一個開始,把每個資料a對應的target-a求出來
		for (int i = 0; i < numbers.length; i++) {
			int value = target - numbers[i];
			// 判斷map裡面有沒有這個target-a,並且下標不是a的下標
			if (map.containsKey(value) && map.get(value) != i + 1) {
				// 如果有獲得該下標
				int index = map.get(value);
				// 判斷該下標是在a前還是後
				if (i + 1 < index)
					result = new int[] { i + 1, index };
				result = new int[] { index, i + 1 };
			}
		}
		return result;
	}

	public static void main(String[] args) {
		int[] numbers = new int[] { 2, 7, 11, 15 };
		int target = 9;
		TwoSum t = new TwoSum();
		int[] result = t.sum(numbers, target);
		System.out.println("[" + result[0] + "," + result[1] + "]");
	}

}

參考閒得思想http://www.jianshu.com/p/627292f44eb3