码迷,mamicode.com
首页 > 其他好文 > 详细

Two sum

时间:2015-05-06 08:01:00      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        
        if(nums == null || nums.length < 2) {
            return null;
        }
        
        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            hm.put(nums[i], i+1);
        }
        
        for (int i = 0; i < nums.length; i++) {
            if (hm.containsKey(target - nums[i])) {
                int index1 = i + 1;
                int index2 = hm.get(target - nums[i]);
                if (index1 == index2) {
                    continue;
                }
                res[0] = index1;
                res[1] = index2;
                return res;
            }
        }
        return res;
    }
}

 

Two sum

标签:

原文地址:http://www.cnblogs.com/77rousongpai/p/4480826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!