LeetCode(1)--Two Sum

題目如下:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

twoSum問題是一道經典的題目,題目要求給定一個整數數組和一個目標整數target,在數組中查找一對數,滿足它們的和正好是target。

解題思路:

使用target = a + b的性質,對數組進行操作。首先,將數組中的值逐個加入map中,然後,對target - nums[i]判斷是否在map中,如果在map中說明a和b已經遍歷過了,最後,將a、b對應的索引返回。提交的代碼:

public int[] twoSum(int[] nums, int target) {
        int[] index = new int[2];
        int length = nums.length;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < length; i++) {
            //把數據存放在mapif(!map.containsKey(nums[i])){ 
                map.put(nums[i], i);
            }
            //判斷map中是否存在target - nums[i]
            if(map.containsKey(target - nums[i])){
                int num = map.get(target - nums[i]);
                if(num < i){
                    index[0] = num + 1;
                    index[1] = i + 1;
                    return index;
                }
            }
        }
        return index;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章