1. Two Sum

Description:

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.
有一個(gè)整型數(shù)組和一個(gè)目標(biāo)值,返回可以兩個(gè)相加的和為目標(biāo)值的下標(biāo)。
每個(gè)輸入有且僅有一個(gè)正確的輸出,每個(gè)元素只能使用一次。

Samples:

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

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

Solutions

<ol>
<li>O(n^2)的解決方案

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if ((nums[i] + nums[j]) == target) {
                    return new int[] {i, j};
                }
            }
        }
        return new int[] {1, 1};
    }
}

因?yàn)樵陬}目中假設(shè)每個(gè)用例有且僅有一個(gè)解,所以下面的return new int[] {1, 1};不會(huì)被執(zhí)行到。這種解法的時(shí)間復(fù)雜度為大O平方階,不需要額外的空間。</li>
<li>O(n)的解決方案

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                result[0] = map.get(target - nums[i]);
                result[1] = i;
                return result;
            }
            map.put(nums[i], i);
        }
        return result;
    }
}

這種方法將每次遍歷的數(shù)值存儲(chǔ)在map中,以值為key,以位置為值,這樣在下次需要這個(gè)值時(shí)從map中取出返回。</li>
</ol>

TestCase

<ol>
<li>[[10,2,3,1,7], 10]</li>
<li>[]

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

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

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