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

[Daily Coding Problem] 1 (LeetCode 1). Find if two numbers in an array add up to k

时间:2018-12-22 11:36:58      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:length   leetcode   一个   个数   list add   odi   get   twosum   rom   

This problem was recently asked by Google.

Given a list of numbers and a number k, return whether any two numbers from the list add up to k.

For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

Bonus: Can you do this in one pass?

 

经典2-sum问题的变形.  最直观的做法是first pass, 用HashMap保存每个数和其index的mapping关系, 然后second pass来寻找是否有满足要求的。 需要注意的一点是,同一个位置的数字不能使用两次.

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

 

1 pass solution 就是一边扫描数组, 一边更新Map。 如果找到满足要求的pair, 直接返回, 否则把当前的数插入到Map中.

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

 

[Daily Coding Problem] 1 (LeetCode 1). Find if two numbers in an array add up to k

标签:length   leetcode   一个   个数   list add   odi   get   twosum   rom   

原文地址:https://www.cnblogs.com/lz87/p/10106326.html

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