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)

你可能感兴趣的:(LeetCode,90,Two-Sum)