Two Sum

https://oj.leetcode.com/problems/two-sum/

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


思路1:對於每一個元素,遍歷尋找另一個元素使得和爲target,時間複雜度O(n^2)。

思路2:先排序,然後首尾兩個指針向中間靠攏,兩指針所指元素大於target,移動尾指針,小於target移動頭指針,直至找到結果或者兩個指針相遇。時間複雜度O(nlogn)。此方法可推廣值3Sum,4Sum等,有待整理。

思路3:利用hashmap,將每個元素值作爲key,數組索引作爲value存入hashmap,然後遍歷數組元素,在hashmap中尋找與之和爲target的元素。 時間複雜度O(n),空間複雜度O(n)。

按照思路一和思路二提交代碼,均Time Limit Exceeded思路三代碼Acceptted

思路一代碼

<pre name="code" class="java">public class Solution {
    public int[] twoSum(int[] numbers, int target) {
     int index[] = new int[3];
     for(int i = 0; i<numbers.length-1;i++){
         for(int j=0; j<numbers.length; j++){
             if(numbers[i]+numbers[j]==target){
                 if(numbers[i]>numbers[j]){
                     index[1] = j+1;
                     index[2] = i+1;
                 }else{
                     index[1] = i+1;
                     index[2] = j+1;
                 }
                 break;
             }
         }
     }
     return index;
    }
}



思路二代碼

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
     int index[] = new int[3];
     bubbleSort(numbers);
       for(int i=0,j=numbers.length-1; i<j; ){
           if(numbers[i]+numbers[j]==target){
               index[1]=i;
               index[2]=j;
               break;
           }
           else if(numbers[i]+numbers[j]>target){j--;}
           else{i++;}
       }
     return index;
    }
    
    public void bubbleSort(int[] num){
       int temp = 0;
       int n = num.length;
       for(int i=0;i<n-1;i++){
           for(int j=0;j<n-i-2;j++){
               if(num[j]>num[j+1]){
                   temp = num[j+1];
                   num[j+1] = num[j];
                   num[j] = temp;
               }
           }
       }         
    }
}


思路三代碼

 

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int len = numbers.length;
        int[] result = new int[2];
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();  
        for(int i = 0; i < len; i++){
            map.put(numbers[i],i);
        }
        for(int i = 0; i < len; i++){
            Integer index = map.get(target-numbers[i]);//HashMap根據key值取出value
            if(index!=null && i < index){//i < index這樣能避免同一個數相加 
                result[0] = i+1;
                result[1] = index+1;
                break;
            }
        }
        return result;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章