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

●中文简要的意思是:给你一个整数的数组,和一个目标值,在数组中找到两个数字,使得这两个数字的加和等于目标值,输出这两个数字的位置坐标。

●解决这个问题的方法有很多,我最先想到的是试探法,即双层的循环,找到合适的就输出,代码如下:

    public int[] twoSum(int[] nums, int target) {
           int[] reslut = new int[2];
        //试探法解决TwoSum
           for(int i=0;i<nums.length;i++){
               for(int j=i+1;j<nums.length;j++){
                   if(nums[i]+nums[j]==target){
                       reslut[0]=i+1;
                       reslut[1]=j+1;
                      return reslut;
                   }
               }
           }
           return reslut;
    }

结果通过:Accepted

●还有另外一种方法,利用HashTable的存贮和查找元素的特性来解决这个问题,代码上只用了一层的循环,但其实资源的消耗上应该或高于第一种方式,因为用了集合数组,必不可少的增加了资源的消耗,且HashTable查找元素的操作底层也肯定是便利了全部的数组元素。

    public int[] twoSum(int[] nums, int target) {
       int[] reslut = new int[2];

       Hashtable<Integer,Integer> list=new Hashtable<Integer,Integer>();

       for(int i=0;i<nums.length;i++){
           Integer n=list.get(nums[i]);
           if(n==null){
               list.put(nums[i],i);
           }

           n=list.get(target-nums[i]);
           if(n!=null){
               reslut[0]=i+1;
               reslut[1]=n+1;
               return reslut;
           }
       }
       return reslut;
    }

二者的效率上都不是很理想,希望读者有更好的解决方案。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专注网赚的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值