淘先锋技术网

首页 1 2 3 4 5 6 7

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.

Example:

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
 给定数组和一个指定的值,返回数组中和为指定值的下标。假设符合条件的最多只有一组,如果没有则返回[0,0]

Step1:声明一个辅助空间hash表,存的<key,value>对应的是<元素值,下标>
Step2:依次遍历数组中的元素,找target-nums[i]是否已经存在hash表中,如果存在则i和hash.get(target-nums[i])即为返回的值,直接返回即可; 否则把<nums[i],i>放到hash表中。

Step3:数组遍历结束之后如果还可以运行到这里,说明没有找到符合要求的两个下标则可以返回[0,0]

/**
	 * 给定数组和一个指定的值,返回数组中和为指定值的下标。假设符合条件的最多只有一组,如果没有则返回[0,0]
	 * Step1:声明一个辅助空间hash表,存的<key,value>对应的是<元素值,下标>
	 * Step2:依次遍历数组中的元素,找target-nums[i]是否已经存在hash表中,如果存在则i和hash.get(target-nums[i])即为返回的值,直接返回即可;
	 * 否则把<nums[i],i>放到hash表中。
	 * Step3:数组遍历结束之后如果还可以运行到这里,说明没有找到符合要求的两个下标则可以返回[0,0]
	 * 遍历数组中的元素的时候首先判断
	 * @date 20150416
	 * @param nums
	 * @param target
	 * @return
	 */
	 public int[] twoSum(int[] nums, int target) {
	        int len = nums.length;
	        int temp[] = {0,0};
	        /*首先判断下数组是否为空,为空则直接返回[0,0]*/
	        if(len <= 0){
	        	return temp;
	        }
	        /*依次遍历数组*/
	        HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
	        for(int i=0;i<len;i++){
	        	if(hash.containsKey(target-nums[i])){
	        		temp[1] = i;
	        		temp[0] = hash.get(target-nums[i]);
	        		return temp;
	        	}else{
	        		hash.put(nums[i], i);
	        	}
	        }
	        
	        return temp;
	    }