leetcode01-Two Sum之beats99.47%Java版本

我的leetcode之旅,该篇章主要完成使用Java实现算法。这是第一篇Two Sum


全部代码下载:
Github链接:github链接,点击惊喜;
写文章不易,欢迎大家采我的文章,以及给出有用的评论,当然大家也可以关注一下我的github;多谢;

1.题目简介:只给英文了

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

2.我的思路:

1.循环记录每个数字,同时判断target-num是否出现过。是就输出
2.第一思路使用hashmap保存数组的出现
2.使用桶记录出现的target-num,比使用hashmap更快 *击败99.47%

3.我的代码

public class Solution {
    //使用桶记录出现的target-num
    public int[] twoSum(int[] nums, int target) {
        int length=nums.length;
        int[] a=new int[]{0,0};
        if(nums==null||length<=0)
          return a;
       int[] tars=new int[100000];//nums[i]正数的桶记录
        int[] tarsf=new int[100000];//nums[i]负数的桶记录
        for(int i=0;i<length;i++){
            int k=target-nums[i];
            if(k<0){
                 if(tarsf[-k]!=0){
                a[0]=tarsf[-k]-1;
                a[1]=i;
                break;
              }else{
                if(nums[i]<0)
                {
                  tarsf[-nums[i]]=i+1;   //i+1是为了将数组初始化的0区分开 
                }
                else
                   tars[nums[i]]=i+1;//i+1是为了将数组初始化的0区分开
            }
            }else{
            if(tars[k]!=0){
                a[0]=tars[target-nums[i]]-1;
                a[1]=i;
                break;
            }else{
                if(nums[i]<0)
                {
                  tarsf[-nums[i]]=i+1;    
                }
                else
                   tars[nums[i]]=i+1;
            }
        }
        }
        return a;
    }
}

4.使用过的低效代码:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int length=nums.length;
        int[] a=new int[]{0,0};
        if(nums==null||length<=0)
          return a;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target-nums[i])) {
                a[0]=map.get(target-nums[i]);
                a[1]=i;
                return a;
            } else {
                map.put(nums[i], i);
            }
        }
        return new int[]{0, 0};
    }
}

好的本章介绍到这里
来自伊豚wpeace(rlovep.com)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值