[Leetcode] Two Sum (Java)
来源:互联网 发布:js的eval方法 编辑:程序博客网 时间:2024/05/29 21:34
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
求数组中两个数的和为给定的target值
首先想到的思路就是排序,然后两个指针,一个从前向后扫,一个从后向前扫,直到相遇,是个O(nlogn)的办法:
import java.util.Arrays;public class TwoSum { public int[] twoSum(int[] numbers, int target) { int start = 0,end = numbers.length-1; int[] tempArray = Arrays.copyOf(numbers, numbers.length); Arrays.sort(tempArray); int temp = tempArray[start]+tempArray[end]; while(temp!=target) { if(temp > target) { end--; } else {start++;} temp = tempArray[start]+tempArray[end]; } int index1=-1,index2=-1; for(int i = 0;i<numbers.length;i++) { if(numbers[i]==tempArray[start] || numbers[i]==tempArray[end]) { if(index1 == -1) { index1 = i; } else if(index2 == -1){index2 = i;break;} } } if(index2<index1){ int tem = index2; index2 = index1; index1 = tem; } return new int[]{index1+1,index2+1}; } public static void main(String[] args) { int[] numbers = {2,7,11,15}; int target = 9;int[] result = new TwoSum().twoSum(numbers, target);System.out.println("index1="+result[0]+",index2="+result[1]);}}觉得太麻烦,又费力又费时,于是改成了Hash,为0(n):
import java.util.HashMap;import java.util.Map;public class TwoSum{ public int[] twoSum(int[] numbers, int target) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0;i<numbers.length;i++) { if(!map.containsKey(target-numbers[i])) { map.put(numbers[i], i+1); }else { return new int[]{Math.min(i+1, map.get(target-numbers[i])),Math.max(i+1, map.get(target-numbers[i]))}; } } return null; } public static void main(String[] args) { int[] numbers = {2,7,11,15}; int target = 9;int[] result = new TwoSum().twoSum(numbers, target);System.out.println("index1="+result[0]+",index2="+result[1]);}}
0 0
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- 【Leetcode】two sum JAVA
- LeetCode java Two Sum
- Two Sum leetcode Java
- [LeetCode][Java] Two Sum
- leetcode:Two Sum 【Java】
- LeetCode|Two Sum-java
- leetcode Two Sum(Java)
- LeetCode – Two Sum (Java)
- [LeetCode java] 1.Two Sum
- LeetCode(001) Two Sum (Java)
- LeetCode 1 Two sum Java
- [leetcode-1]Two Sum(java)
- LeetCode – Two Sum (Java)
- LeetCode 1 - Two Sum ( JAVA )
- LeetCode(java)1. Two Sum
- leetcode 1. Two Sum -----java
- 12.4带说明幻灯片
- mac 命令行忽略大小写
- Sftp和ftp 区别、工作原理
- ajax json 传值注意
- source命令与点命令(.)
- [Leetcode] Two Sum (Java)
- DBCC大全集之(适用版本MS SQLServer 2008 R2)----DBCC PROCCACHE以表格格式显示有关过程缓存的信息
- cppquery:用C++模仿jquery的探索
- php验证码类
- Eclipse安装SVN插件
- Pomelo 新手入门(一)
- Unity 基础知识
- 关于SharedPreferences 保存list数据到持久层
- jq获取表单值与赋值代码