LeetCode第一题Two Sum

       好了,今天给大家介绍的是LeetCode上面的第一道题,原题链接为https://leetcode.com/problems/two-sum/,别小看这一题哦,他后来会演化出threesum,foursum等问题,接下来就为大家介绍解法。

题目如下:     

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

翻译过来就是给出一个数组,找出这个数组中的两个元素,使得两者的和为一个特定值(假设题目只有一个解)

看到这道题,相信大部分童鞋的第一个想法就是遍历两遍数组,用穷举法找出这两个下标:

 

for(int i=0;i<nums.length;i++){

   for(int j=0;j<nums.length;j++){

         if(nums[i]+nums[j]==target){

             break;

         }

    }

}

   显然这个方法不是我们心中想要的解法,它的复杂度是o(n^2),而且没有用到我们学习到的数据结构,使用的只有简单的数组。

   这个时候题干上所说:返回两个下标提示了我们解题的思路。既然让我们返回的是数组的下标(如果返回的是数组的值,那么以后我们在threesum中会有讨论),那么我们可以想到,可不可以建立一个hashtable,使得数组的值为hashtable的键,数组的下标为hashtable的值呢?这样的话,我们只需要线性遍历一遍数组,获取数组中元素的值nums[i],然后用target-nums[i]到hashtable中获取到另外一个数的下标j即可。

   代码如下:

     

int m=0;
    int n=0;
    Hashtable<Integer, Integer> test = new Hashtable<Integer, Integer>();//建立储存数组值和下标对应的得hashtable
    for(int i=0;i<nums.length;i++){
    test.put(nums[i], i+1);  //将数组值和下标对应的得hashtable
    }
    for(int i=0;i<nums.length;i++){
    if(test.containsKey(target-nums[i])){  //从nums[i]寻找到nums[j],使得两者和为target,然后根据nums[j]从hashtable中找到对应的j
      n=(int) test.get(target-nums[i]);
      m=i+1;
      if(m!=n){
         break;
      }
    }
    }
    int a[]={Math.min(m, n),m+n-Math.min(m, n)};//按从小到大返回下标
        return a;


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值