果果1020

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

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

 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         if (nums == null || nums.length < 2) {
 4             return null;
 5         }
 6         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
 7         for (int i = 0; i < nums.length; i++) {
 8             int r = target - nums[i];
 9             if (map.containsKey(r)) {
10                 return new int[] { map.get(r), i };
11             } else {
12                 map.put(nums[i], i);                
13             }
14         }
15         return null;
16     }
17 }

 

posted on 2017-01-02 12:10  果果1020  阅读(113)  评论(0)    收藏  举报