LeetCode-array-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.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

意思明確,返回?cái)?shù)組中兩數(shù)和為target值得下標(biāo)

代碼如下:

public class TwoSum {
    public static void main(String[] args) {
        TwoSumImpl t = new TwoSumImpl();
        int s[] ={5,2,5, 11};
        int tag = 10;
        int [] result = t.twoSum(s,tag);
        System.out.println(" ======= "+Arrays.toString(result));
    }
}

class TwoSumImpl {
    public  int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) { // 核心
                System.out.println(map);
                result[1] = i ; //i的順序和數(shù)組的下標(biāo)一致
                result[0] = map.get(target - numbers[i]);
                return result;
            }
            //最開始我是將數(shù)組中所有的值先put進(jìn)去,在這個(gè)for循環(huán)外面,發(fā)現(xiàn),數(shù)組有重復(fù)數(shù)字
            //行不通,,,智商壓制
            map.put(numbers[i], i );
        }
        return result;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,923評論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,132評論 0 23
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,660評論 5 6
  • 他們是春天里的星星點(diǎn)點(diǎn)。四季的燎原之火。每天,我都要看看他們,希望他們快快長大。更樂意記錄他們的生長過程。現(xiàn)在這個(gè)...
    楓林上學(xué)閱讀 425評論 2 1
  • 社會(huì)主義好。日本宜家一不提供網(wǎng)上下單服務(wù),二不提供現(xiàn)場下單服務(wù)......一切商品都要自己拿到結(jié)賬的地方去結(jié)賬,包...
    GSES94閱讀 165評論 2 0

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