Leetcode——1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.java

You may assume that each input would have exactly one solution.spa

Example:
code

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

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

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.orm

import java.util.Hashtable;
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int index[]=new int[2];
		Hashtable<Integer, Integer> hashTable = new Hashtable<Integer, Integer>();
		for(int item=0;item<nums.length;item++){
			if(hashTable.get(nums[item])==null&&hashTable.get(target-nums[item])==null){
				hashTable.put(nums[item], item);
			}else if(hashTable.get(target-nums[item])!=null){
				index[1] = item;
				index[0] = hashTable.get(target-nums[item]);
				break;
			}
		}
		return index;
    }
}
相關文章
相關標籤/搜索