001_TwoSum

/***
 * 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].
 *
 */

 

public class N001_TwoSum {
    /***
     * 暴力搜索 時間複雜度是o(n2) ,捨棄
     *
     * hashmap是常數級的查找效率
     * 這樣咱們在遍歷數組的時候,用target減去遍歷到的數字,就是另外一個須要的數字了,直接在HashMap中查找其是否存在便可
     * 注意要判斷查找到的數字不是第一個數字
     */
    public static int[] find(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) {
            if (m.containsKey(target - nums[i])) {
                res[0] = m.get(target - nums[i]);
                res[1] = i; // 此時 i 對應的元素尚未放進去。
                return res;
            }
            m.put(nums[i], i);
        }
        return res;
    }

    public static void main(String args[]) {
        int target = 14;
        int[] nums = {2, 7, 11, 15};
        int[] result = find(nums, target);
        for (int num : result) {
            System.out.println(num);
        }
    }
}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息