LeetCode算法題之第1題Two Sum

Question:

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.

Example:

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

解決:

問題是要從數(shù)組中找到兩個數(shù)據(jù),使得兩數(shù)之和等于目標值,輸出該兩數(shù)的下標(從0開始)。顯而易見,這里最簡單的是O(n^2)的時間復雜度的解決辦法。

public static int[] twoSum(int[] nums, int target) {
    int[] answer = new int[2];
    A:for (int i = 0; i < nums.length; ++i){
        answer[0] = i;
        int b = target - nums[i];
        for (int j = i + 1; j < nums.length; ++j){
            if (nums[j] == b){
                answer[1] = j;
                break A;
            }
        }
    }
    return answer;
}

考慮O(n)的算法,可以使用map使得查找的復雜度降為O(1)。

public int[] twoSum(int[] nums, int target) {
    int[] answer = new int[2];
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; ++i){
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; ++i){
        int b = target - nums[i];
        if (map.containsKey(b) && i != map.get(b))
            return new int[]{i, map.get(b)};
     }
     return answer;
}

代碼地址(附測試代碼):
https://github.com/shichaohao/LeetCodeUsingJava/tree/master/src/TwoSum

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容