Two Sum两数之和

开始LettCode的刷题之旅,坚持!

平生不识TwoSum,刷尽LeetCode也枉然

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 static int[] TwoSum(int[] arr,int target){
		HashMap hashMap=new HashMap();
		int[] result=new int[2];
		for(int i=0;i
public int[] TwoSum(int[] nums, int target) {
        HashMap m = new HashMap();
        int[] res = new int[2];
        for (int i = 0; i < nums.length; ++i) {
            if (m.containsKey(target - nums[i])) {
                res[0] = i;
                res[1] = m.get(target - nums[i]);
                break;
            }
            m.put(nums[i], i);
        }
        return res;
    }

 

你可能感兴趣的:(LeetCode)