1.Two Sum(Easy)

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.
給定一個整數(shù)數(shù)組,返回兩個數(shù)的下標,使這兩個數(shù)的和等于指定的目標數(shù),假定每個輸入的數(shù)組都有恰好一個解

Example:

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

My Solution

(Java) Version 1 Time: 98ms:

  在數(shù)組中從前往后搜索,每一個數(shù)都和其余的數(shù)進行求和判斷,如果有結(jié)果則直接輸出,題目中已經(jīng)假設(shè)只有一個解,不需要再向后搜索

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

(Java) Version 2 Time: 52ms:

  對上一個算法的改進在于,第一次循環(huán)搜索的數(shù)之前的數(shù)不需要再在第二個循環(huán)重新判斷一次,每一次循環(huán)都只需要和后面的數(shù)作比較,前面的數(shù)在上一次循環(huán)中已經(jīng)被比較過一次了,同時,因為不需要同前面的數(shù)進行比較,那么,比較可以跳過自己,直接從i+1開始,省去了判斷i==j的步驟

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 nums;
    }
}

(Java) Version 3 Time: 8ms (By plover ):

  運用Java的Map,構(gòu)造Map鍵為當(dāng)前判斷的數(shù)的期望目標數(shù),值為數(shù)的下標,通過搜索鍵來判斷是否存在對應(yīng)的期望目標數(shù),并可以快速找到其下標,不需要重新循環(huán)一次。巧妙應(yīng)用Map把數(shù)組中的數(shù)和下標綁定在一起,達到快速獲得數(shù)及其下標的目的

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> pair=new HashMap<>();
        int result[] = new int[2];
        for(int i=0;i<nums.length;i++){
            if(pair.containsKey(nums[i])){
                result[0]=pair.get(nums[i]);
                result[1]=i;
                return result;
            }
            else{
                pair.put(target-nums[i], i);
            }
        }
    return result;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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