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

LeetCode 1:Two Sum

时间:2015-10-13 20:54:52      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

用 Hash Table 实现

Time : O(n)

Space: O(n)

 

import java.util.HashMap;

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap< Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target-nums[i])) {
                int[] result = {map.get(target-nums[i])+1, i+1};
                return result;
            }
            map.put(nums[i], i);
        }
        return null;
    }
    
    public static void main(String[] args) {
        Solution solu = new Solution();
        int[] a = {2, 7, 11, 15};
        int target = 9;
        int[] result = solu.twoSum(a, target);
        for (int i = 0; i < result.length; i++)
            System.out.println(result[i]);
    }
}

 

 

 

2015-10-13

 

LeetCode 1:Two Sum

标签:

原文地址:http://www.cnblogs.com/whuyt/p/4875503.html

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