LeetCode---1.Two Sum

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

問(wèn)題描述:

在給定的一個(gè)數(shù)組中超出兩個(gè)數(shù)字,讓這個(gè)兩個(gè)數(shù)字之和等于一個(gè)給定的值。假設(shè)數(shù)組中至少存在一組滿足要求。

解題思路:

1.窮舉法 暴力求解

遍歷所有的兩個(gè)數(shù)之和,直到找到等于目標(biāo)值的兩個(gè)數(shù)即可。該方法的時(shí)間復(fù)雜度為O(n2)

public int[] twoSum(int[] nums, int target) {
    int[] result = new int[2];
    if (nums == null || nums.length < 2) return result;

    for (int i = 0; i < nums.length - 1; i++) {
        for (int j = i + 1; j < nums.length; j++) {

            if (nums[i] + nums[j] == target) {
                result[0] = i;
                result[1] = j;
                break;
            }
        }
    }

    return result;
}

2.hash法 以空間換時(shí)間 O(N)

用hash表去存儲(chǔ)目標(biāo)值和其中一個(gè)數(shù)字之差在數(shù)組中的位置

public int[] twoSum(int[] nums, int target) {

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

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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