LeetCode 1 Two Sum
来源:互联网 发布:淘宝购物信用上征信吗 编辑:程序博客网 时间:2024/06/08 16:26
Two Sum
Total Accepted: 87651 Total Submissions: 497199My SubmissionsGiven 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
首先想到是两个for循环,执行的时间为O(n*n),发现系统提交上面显示超时,下面为代码:
public int[] twoSum(int[] nums, int target) {int a[] = new int[2];for (int i = 0; i < nums.length; i++)for (int j = 0; j < nums.length; j++) {if (nums[i] + nums[j] == target) {a[0] = i + 1;a[1] = j + 1;}}Arrays.sort(a);return a;}
然后想到先将数组排序,找到<target的最大位置i和<target/2的最大位置j,然后将其两个for循环,其时间复杂度为O(n/2*n/2),还要改进。
最后想到是用hashtable或者hashmap来做,使得时间复杂度为线性的即O(n),下面为代码:public int[] twoSum(int[] nums, int target) {int a[] = new int[2];HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();for (int i = 0; i < nums.length; i++) {Integer n = map.get(nums[i]);if (n == null)map.put(nums[i], i);n = map.get(target - nums[i]);if (n != null && n < i) {a[0] = n + 1;a[1] = i + 1;return a;}}return a;}
0 0
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- leetcode 1:Two Sum
- LeetCode 1 Two Sum
- leetcode #1 two sum
- 写一个“标准”宏,这个宏输入两个参数并返回较小的一个
- Oracle数据库mybatis 插入空值时报错(with JdbcType OTHER)
- Mac 使用SSH远程登录
- p122,17
- 2066 一个人的旅行
- LeetCode 1 Two Sum
- AngularJS学习(一)
- (C语言)字符串比较函数
- [转载] Android Studio Rendering Problems "android.support.v7.internal.widget.ActionBarOverlayLayout"
- spring定时任务
- 使用Combox控件的一个问题
- 离线安装gradle
- subplot上标记、画图
- js中的闭包之我理解