LeetCode - Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

先来一个超时的暴力算法:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public class Solution {  
  2.     public int[] twoSum(int[] numbers, int target) {  
  3.         int[] res = new int[2];  
  4.         for (int i = 0; i < numbers.length-1; i++){  
  5.             for (int j = i+1; j < numbers.length; j++){  
  6.                 if(numbers[i] + numbers[j] == target){  
  7.                     res[0] = i+1;  
  8.                     res[1] = j+1;  
  9.                     return res;  
  10.                 }  
  11.             }  
  12.         }  
  13.         return res;  
  14.     }  
  15. }  



two sum 和之后的 three sum 以及 4 sum 都简单了许多,这里的解法是吧 所有 numbers 中的元素以及他们所对应的 1-based index 关系存储在 map 中,

然后遍历整个数组,确立一个 index ,找 target - numbers[ i ] 的 index ,找到就是结果。

这题不能用 sort 解决 sum3 sum4 的方法, 因为题目要求返回的是原数组的 index 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. //use hashmap hash all element in that array, then find if the map contains target - numbers[i]   
  2.   
  3. public class Solution {  
  4.     public int[] twoSum(int[] numbers, int target) {  
  5.         if (numbers == null || numbers.length < 2){  
  6.             return null;  
  7.         }  
  8.           
  9.         int[] res = new int[2];  
  10.         Map<Integer, Integer> map = new HashMap<>();  
  11.         for (int i = 0; i < numbers.length; i++){  
  12.             map.put(numbers[i], i+1);  // 保存 元素和 index 关系(index 转换成1 base )  
  13.         }  
  14.           
  15.         for (int i = 0; i < numbers.length-1 ; i++){  
  16.             if (map.containsKey(target-numbers[i])){  
  17.                 int index1 = i+1;  
  18.                 int index2 = map.get(target-numbers[i]);  
  19.                 if (index1 == index2){  
  20.                     continue;  
  21.                 }  
  22.                 res[0] = index1;  
  23.                 res[1] = index2;  
  24.                 return res;  
  25.             }  
  26.         }  
  27.         return res;  
  28.     }  
  29. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值