Leetcode1--->数组中两数之和等于给定数
题目: 给定一个数组nums,目标数target.在数组中找到两数之和为target的数,返回两数的下标
举例:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
思路:将数组中的数存储在Hashtable中,当遍历到i位置时,判断已经是否有数=target-nums[i],直到遍历结束位置。Hashtable中的key = nums[i],value = i;
1 import java.util.Hashtable; 2 public class Solution { 3 public int[] twoSum(int[] nums, int target) { 4 int[] a = new int[2]; 5 Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>(); 6 for(int i = 0; i < nums.length; i++) 7 { 8 Integer n = ht.get(nums[i]); 9 if(n == null) 10 { 11 ht.put(nums[i], i); 12 } 13 n = ht.get(target - nums[i]); 14 if(n != null && n < i) 15 { 16 a[0] = n; 17 a[1] = i; 18 return a; 19 } 20 } 21 return a; 22 23 } 24 }