[LeetCode]Two Sum

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);
        }
        int[] result = new int[2];
        for(int i = 0; i < numbers.length; i++) {
            Integer index2 =  num.get(target - numbers[i]);
            if(index2 != null && index2 != i) {
                result[0] = i+1;
                result[1] = index2+1;
                return result;
            }
        }
        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.

posted on 2015-04-02 04:13  Seth_L  阅读(149)  评论(0编辑  收藏  举报