[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
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- 上课觉得刚好鬼离开家就很尴尬
- 2015.04.01 Leetcode Insert interval
- 坑坑的程序员
- [LinkedIn] Word Distance Finder (Find distance in dictionary)
- 一切成功源于积累——20150401 黄金 2800点
- [LeetCode]Two Sum
- ruby on rails rotate log file(日志文件)
- [LinkedIn] String Permutation
- ADSL拨号
- Best Time to Buy and Sell Stock IV
- HTTP深入浅出 http请求
- 关于goto语句
- 【无中生有】---1---技术选型
- android viewpager