Leetcode-1 Two Sum(Java) -by zzy

chenxi379630452發表於2015-03-28

Problems:
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

Answers:
1,雙重迴圈
Time complexity in worst case: O(n^2).

public static int[] twoSum(int[] numbers, int target) {
    int[] ret = new int[2];
    for (int i = 0; i < numbers.length; i++) {
        for (int j = i + 1; j < numbers.length; j++) {
            if (numbers[i] + numbers[j] == target) {
                ret[0] = i + 1;
                ret[1] = j + 1;
            }
        }
    }
    return ret;
}

2,Hashtable

import java.util.Hashtable;
public class Solution {
    public int[] twoSum(int[] numbers, int target) {

        Hashtable<Integer,Integer> ht = new Hashtable<Integer,Integer>();
        int[] result = new int[2];

        for(int i = 0; i < numbers.length; i++ ){
            if(ht.get(target-numbers[i]) != null){//當標誌值減去當前值在hashtable裡存在,即和減去其中一個值=另一個值已存在,則返回那個值的下標 ps:null一定要小寫,一定要引入import包
            result[0] = ht.get(target-numbers[i])+1;//將當前陣列值的下標取到,即hashtable得value
            result[1] = i+1;
            break;
            }else{
                ht.put(numbers[i],i);//用key存陣列值而value存下標
            }
        }
        return result;
    }
}

3,HashMap
Use HashMap to store the target value.

public class Solution {
    public int[] twoSum(int[] numbers, int target) {

        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
   int[] result = new int[2];

for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(numbers[i])) {
int index = map.get(numbers[i]);
result[0] = index+1 ;
result[1] = i+1;
break;
} else {
map.put(target - numbers[i], i);
}
}

return result;
    }
}

The 2 and 3 solutions are better than 1.
Time complexity depends on the put and get operations of HashMap/Hashtable which is normally O(1).

Time complexity of thesw solutions: O(n).

The deferences between hittable and hash map:(轉自百度經驗)
1、繼承類不同:
A.HashMap繼承AbstractMap
B.Hashtable繼承Dictionary
2、執行效率不同:
A.HashMap是非執行緒安全的,是Hashtable的輕量級實現,效率較高
B.Hashtable是執行緒安全的,效率較低
3、put方法對key和value的要求不同
A.HashMap允許Entry的key或value為null
B.Hashtable不允許Entry的key或value為null,否則出現NullPointerException
4、有無contains方法
A.HashMap沒有contains方法
B.Hashtable有contains方法
5、Hashtable和HashMap它們兩個內部實現方式的陣列的初始大小和擴容的方式。HashTable中hash陣列預設大小是11,增加的方式是 old*2+1。HashMap中hash陣列的預設大小是16,而且一定是2的指數。
6、Hashtale是Syncchronize的,而HashMap是Asyncchronize的,當多個執行緒訪問Hashtable時,Hashtable不需要自己為它的方法實現同步;而當多個執行緒訪問HashMap時,需要通過Collections.synchronizedMap來同步HashMap。

參考:http://oznyang.iteye.com/blog/30690

相關文章