LeetCode——No.1 TwoSum

原始题目:

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

题目翻译:
给出一个整数数组,使数组中的两个数等于一个特定的数,并返回这两个数的下标。
你可以假定每次输入的数组都有一个确定的解决办法,同时你不能使用同一个元素两次。

下面是Java的代码

public class Solution {  
    public int[] twoSum(int[] numbers, int target) {  
        HashMap<Integer, Integer> hashmap = new HashMap<Integer, Integer>();  
        int[] result = new int[2];  
        for (int i = 0; i < numbers.length; ++i) {  
            if (hashmap.get(target - numbers[i]) != null) {  
                result[0] = hashmap.get(target - numbers[i]) ;  
                result[1] = i ;  
                break;  
            } 
            else {  
                hashmap.put(numbers[i], i);  
            }  
        }  
        return result;  
    }  
}

猜你喜欢

转载自blog.csdn.net/wardseptember/article/details/79539091