Two Sum

来源:互联网 发布:北电网络交换 编辑:程序博客网 时间:2024/06/05 08:32

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;    }}



0 0
原创粉丝点击