LeetCode1: TwoSum

来源:互联网 发布:密松水电站 知乎 编辑:程序博客网 时间:2024/06/14 04:07

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

public class Solution {    public int[] twoSum(int[] numbers, int target) {        // Start typing your Java solution below        // DO NOT write main() function        for(int i=0, j=0; i < numbers.length; i++){            for(j=i+1; j < numbers.length; j++){                if(numbers[i] + numbers[j] == target)                    return new int[] {i+1, j+1};            }        }        return null;    }}

O(n) Solution:

public class Solution {    public int[] twoSum(int[] numbers, int target) {        // Start typing your Java solution below        // DO NOT write main() function        HashMap<Integer, Integer> exist = new HashMap<Integer, Integer>();        int [] res = new int[2];        for(int i=0; i< numbers.length; i++){            exist.put(numbers[i], i);        }        for(int i=0; i< numbers.length; i++){            if(exist.get(target - numbers[i]) !=null){                res[0] = i+1;                res[1] = exist.get(target-numbers[i])+1;                if(res[0] > res[1]){                    int tmp = res[0];                    res[0] = res[1];                    res[1] = tmp;                }                return res;            }        }        return null;    }}


------------------------------------------------------------------------------------------------------------------------------------------

LL's solution:

public class Solution {    public int[] twoSum(int[] numbers, int target) {        // Start typing your Java solution below        // DO NOT write main() function        int len = numbers.length;        HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();        int i;        for(i = 0; i<len; i++)            hash.put(numbers[i],i);        for(i=0;i<len; i++){            int newTarget = target-numbers[i];            if(hash.containsKey(newTarget))                return new int[]{i+1,hash.get(newTarget)+1};                        }        return null;    }}


原创粉丝点击