leetcode-question1

題目描述

給定一個整數數組和一個目標值,找出數組中和爲目標值的兩個數。你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。

示例:

給定 nums = [2, 7, 11, 15], target = 9 因爲 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

思路

運用HashMap來存儲數組中元素的位置,用target減去元素中的某一個值,並記錄這個元素在數組中的位置,如果得到的結果值是數組中的某一個元素,則通過map獲取它在數組中的位置,然後返回。

代碼

import java.util.HashMap;
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int [] ret = new int[2];
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i = 0;i < nums.length;++ i){
           map.put(nums[i],i);
        }
        for(int i = 0; i < nums.length;++ i){
            int tem = target - nums[i];
            if(map.get(tem) != null && map.get(tem) != i){
                ret[0] = i;
                ret[1] = map.get(tem);
                return ret;
            }
        }

        return ret;

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章