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.

Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

大致意思就是給定一個整數(shù)數(shù)組,找出其中兩個數(shù)滿足相加等于指定的目標數(shù)字,返回這個兩個數(shù)的數(shù)組下標。
同時題目還給出了一個隱含的條件:有且只有一個解 —— 數(shù)組中的元素不重復

有半年沒刷題了,開始的時候沒有好的思路,先用最笨的方法解決這個問題,二重循環(huán),時間復雜度O(n^2)

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

        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if ((nums[j]) == target - nums[i]) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

提交通過之后,查看Editorial找到了更好的解法:使用HashMap,由element映射index,遍歷至數(shù)組元素element時查找HashMap中是否已存在key等于target - element,若存在即可從HashMap中取出其下標,若不存在則向HashMap中裝入(element, index),這樣只需遍歷數(shù)組一次,而在HashMap中的每次查詢時間復雜度均為O(1),所以總的時間復雜度O(n)

import java.util.HashMap;

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

        int[] result = new int[2];
        Map<Integer, Integer> elementToIndex = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (elementToIndex.containsKey(target - nums[i])) {
                result[0] = elementToIndex.get(target - nums[i]);
                result[1] = i;
                return result;
            }
            elementToIndex.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

以前幾乎沒在LeetCode上刷過題,現(xiàn)在題目總數(shù)已經(jīng)增加到429道了,短時間內(nèi)是刷不完了,刷題在精不在多,爭取明年暑假之前把一些經(jīng)典的題目多刷幾遍。另外只用自帶的編輯器寫代碼,堅決不用IDE!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容