[LeetCode]1. Two Sum
来源:互联网 发布:windows vista系统重装 编辑:程序博客网 时间:2024/06/11 17:03
Problem Description
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
[https://leetcode.com/problems/two-sum/]
思路
先把每个数字的位置用hashtable保存下来,这里要注意会有相同的数字,所以我用了两个hashtable,毕竟相同的数字如果要作为答案的话,只需要前两个位置的数字即可。
然后将nums排序,方便剪枝。
之后就是两层循环就好了。
如果用DP会不会更快呢?~
Code
package Q1;import java.util.Arrays;import java.util.Hashtable;public class Solution { public static int getMax(int[] nums) { int max = 0; for (int i = 0; i < nums.length; i++) max = Math.max(max, nums[i]); return max; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static int[] twoSum(int[] nums, int target) { int[] ans = { 0, 0 }; Hashtable index1 = new Hashtable(); Hashtable index2 = new Hashtable(); for (int i = 0; i < nums.length; i++) { if (index1.containsKey(nums[i]) && !index2.containsKey(nums[i])) { index2.put(nums[i], i + 1); } else if (!index1.containsKey(nums[i])) index1.put(nums[i], i + 1); } int tmp = 0; Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { for (int j = 0; j < nums.length; j++) { tmp = nums[i] + nums[j]; if (tmp > target) break; else if (tmp == target) { if (nums[i] == nums[j]) { ans[0] = Integer.parseInt(index1.get(nums[i]) .toString()); ans[1] = Integer.parseInt(index2.get(nums[j]) .toString()); } else { ans[0] = Integer.parseInt(index1.get(nums[i]) .toString()); ans[1] = Integer.parseInt(index1.get(nums[j]) .toString()); } Arrays.sort(ans); return ans; } } if (nums[i] > target) break; } return ans; } // public static void main(String[] args) { // int a[]={-1,-2,-3,-4,-5}; // int t=-8; // int[] ans=twoSum(a, t); // System.out.print(ans[0]+" "+ans[1]); // // }}
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
- 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
- .Net专版-memcached在windows下的下载与安装
- CFS中的虚拟运行时间
- jekyll 2 升级 jekyll 3 Dependency Error
- 百思学习笔记02-设置tabbar
- android studio 图片资源的放置位置
- [LeetCode]1. Two Sum
- Hadoop—MapReduce练习(数据去重、数据排序、平均成绩、倒排索引)
- 百度对象存储BOS(Baidu Object Storage)进行冷存储数据备份
- 统计字母,数字,空格的个数
- 【时光碎片】寻找记忆里的春节
- C#百度网盘批量转存助手工具_绿色安全版 百度云盘一键转存小黄人软件原创20161204已测可用
- 查找算法
- 关于php的魔术常量
- CAS部署错误1:Ticket验证异常org.jasig.cas.client.validation.TicketValidationException: