Two Sum
来源:互联网 发布:成都黑马程序员怎么样 编辑:程序博客网 时间:2024/06/14 04:26
题目:
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[] nums, int target) { int[] a = new int[2]; int flag = 0; int temp = nums.length; for (int i = 0;i < temp-1;i++) { for (int j = i+1;j < temp;j++) { if (nums[i] + nums[j] == target) { a[0] = i+1; a[1] = j+1; flag = 1; break; } } if (flag == 1) { break; } } return a; }}
后来看了下讨论区,有O(n)的算法。首先是利用了Java HashMap的get()和put()的时间复杂度在没有冲突的情况下为O(1)的特性,然后因为a + b = target, 遍历的时候用target-b做键,下标做值,放入哈希表,又用a做键去找,能找到则a = target - b,即a + b = target。代码如下:
public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> hasnMap = new HashMap<>(); for (int i = 0;i < nums.length;i++) { if (hasnMap.get(nums[i]) != null) { return new int[]{hasnMap.get(nums[i])+1,i+1}; } hasnMap.put(target-nums[i],i); } return new int[]{}; }}
0 0
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- 文本转语音
- 纯HTML5+JS+PHP批量上传
- 用JavaScriptCore做android和iOS都兼容的JS-NativeSDK
- udev规则
- listControl添加鼠标浮动提示
- Two Sum
- kali攻防第4章 内网称霸之HTTP信息截取
- VS2010生成Excel报表
- 目前国内最全面的介绍-Android 中的BroadCastReceiver
- wifi测试相关
- 启动活动的最佳写法
- 新建用户时的注意事项
- c++11细粒度的线程安全
- spark RDD系列------2.HadoopRDD分区的创建以及计算