(leetcode)1. 查找数组中两个数之和为给定值Two Sum---Java

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

给定一个整数数组,返回两个数字的索引,使得它们相加到一个特定的目标。

您可以假设每个输入都有一个解决方案。

Given nums = [2, 7, 11, 15], target = 9,

Because nums[ 0] + nums[ 1] = 2 + 7 = 9,
return [ 01].

 我的解法:思路是把数组装进arraylist列表里面,然后做一次循环,每次用列表里面的第i个数和后面的第n-i个数做判断。这样做没有最快的答案好,但是思路是一样的,原因在于,

我是先一次性全部放进去,这里花时间。然后,每次比较,我又取了全部list的子列表arraylist,这里也花时间。

public int [] twoSum( int [] nums , int target ) {
      List<Integer> s = new ArrayList<Integer>();
       int len = nums . length ;
       for ( int i =0; i < len ; i ++){
             s .add( nums [ i ]);
      }
      
       //Collections.sort(s);
      
       for ( int i =0; i < len -1; i ++){
  //              System.out.println(i+" i  " +  len+ "  len");
  //               System.out.println(s.subList(i+1, len)+"    "+(target-nums[i]));
             if ( s .subList( i +1, len ).contains( target - nums [ i ])){
                   int [] res = new int [2];
                   res [0] = i ;
                   res [1] = 1+ i + s .subList( i +1, len ).indexOf( target - nums [ i ]);
                   return res ;
            }
      }
       return null ;
    }

标准算法:

   
   
    public int [] twoSum2( int [] numbers , int target ) {
        int [] result = new int [2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for ( int i = 0; i < numbers . length ; i ++) {
            if ( map .containsKey( target - numbers [ i ])) {
                result [1] = i ;
                result [0] = map .get( target - numbers [ i ]);
                return result ;
            }
            map .put( numbers [ i ], i );
        }
        return result ;
    }

放在hashmap里面,这样,在找到值的时候,去找对应的键就很快,比arraylist中的indexof要快,
另外,采用倒叙的方式,每次比较,比不到就加一个,加一个比截取一大段复杂度要低很多。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值