Two Sum

发布时间:2017-2-21 13:17:52 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"Two Sum",主要涉及到Two Sum方面的内容,对于Two Sum感兴趣的同学可以参考一下。

//use hashmap, time: o(n), space: o(n) //if the array if already sorted, we can use two pointers, it will be linear time and space // through we can use two pointers here, it will be o(nlogn) time and o(n) sapce because we need to keep the index of the array  public int[] twoSum(int[] numbers, int target) { // Start typing your Java solution below // DO NOT write main() function HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] result = new int[2]; for(int i = 0; i < numbers.length; i++) { if(!map.containsKey(numbers[i])) { map.put(target - numbers[i], i); }else{ result[0] = map.get(numbers[i]) < i ? map.get(numbers[i]) + 1 : i + 1; result[1] = map.get(numbers[i]) < i ? i + 1 : map.get(numbers[i]) + 1; break; } } return result; }

上一篇:折扣&折让-看清实质的思考
下一篇:Ubuntu安装Arduino及使用Emacs开发环境设置

相关文章

关键词: Two Sum

相关评论