[LeetCode]Two Sum

来源:互联网 发布:sql 计算查询结果合计 编辑:程序博客网 时间:2024/05/19 23:52
public class Solution {    public int[] twoSum(int[] numbers, int target) {        HashMap<Integer, Integer> num = new HashMap();        for(int i = 0; i < numbers.length; i++) {            num.put(numbers[i], i);        }        for(int i = 0; i < numbers.length; i++) {            //try to see if the difference is in the hashmap            Integer index2 =  num.get(target - numbers[i]);            if(index2 != null && index2 != i) {                //only add 1 here if the array is designed strangely                return new int[] {i+1, index2+1};            }        }        return null;    }}

另一种,design an interface for it.

题目:

public interface TwoSum { /**  * Stores @param input in an internal data structure.  */ void store(int input); /**  * Returns true if there is any pair of numbers in the internal data structure  * which have sum @param val, and false otherwise.  * For example, if the numbers 1, -2, 3, and 6 had been stored,  * the method should return true for 4, -1, and 9, but false for 10, 5, and 0  */ boolean test(int val);}

解答(用的是夹逼法)

public class TwoSumImpl implements TwoSum {   private List<Integer> array; public TwoSumImpl() {   this.array = new ArrayList<Integer>(); } @Override public void store(int input) {   array.add(input); } @Override public boolean test(int val) {   Collections.sort(array);         // O(nlogn)   int i = 0, j = array.size()-1;   while (i < j) {     if (array.get(i) + array.get(j) == val) return true;     else if (array.get(i) + array.get(j) < val) ++i;     else ++j;   }   return false; }}

follow-up: to optimize the performance, we can use a cache for caching the previously computed results.

0 0
原创粉丝点击