1. 程式人生 > >leetcode01-Two Sum之beats99.47%Java版本

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)