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

LeetCode Two Sum

时间:2015-12-12 07:04:55      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/two-sum/

Time Complexity: O(n). Space: O(n).

AC Java:

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

 

LeetCode Two Sum

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5040710.html

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