Leetcode-Two Sum
来源:互联网 发布:成都真那么好么知乎 编辑:程序博客网 时间:2024/06/07 15:48
Two Sum
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
AC代码:
import java.util.Arrays;class Pair implements Comparable<Pair>{int val;int index;public Pair( int val, int index ){this.val = val;this.index = index;}@Overridepublic int compareTo(Pair other) {// TODO Auto-generated method stubreturn this.val - other.val;}}public class Solution { public int[] twoSum(int[] numbers, int target){int result[] = new int[2];//store indexint index[] = new int[numbers.length];//relate number and indexPair pairs[] = new Pair[numbers.length];for( int i=0; i<numbers.length; i++){pairs[i] = new Pair(numbers[i],i+1);}//1 sortArrays.sort(pairs);//2 find index int pre = 0, last = numbers.length-1;while( pre < last ){if( pairs[pre].val + pairs[last].val == target ){if( pairs[pre].index < pairs[last].index){result[0] = pairs[pre].index;result[1] = pairs[last].index;}else{result[0] = pairs[last].index;result[1] = pairs[pre].index;}break;}else if( pairs[pre].val + pairs[last].val < target){pre++;}else if( pairs[pre].val + pairs[last].val > target ){last--;}}return result; } }
超时代码(时间复杂度O(n*n)):
public int[] twoSum(int[] numbers, int target){int result[] = new int[2];for( int i=0; i<numbers.length; i++ ){for( int j=i+1; j<numbers.length; j++){if( numbers[i]+numbers[j] == target ){result[0] = i+1;result[1] = j+1;break;}}}return result;}
0 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- 购物类APP之王——淘宝安卓版(一)
- Python--ctypes
- android开发步步为营之26:进度条对话框ProgressDialog的用法
- oracle 10gR2 监听器启动报错1067同时操作系统日志报: 错误模块名称: ntdll.dll
- C#中的ICollection接口
- Leetcode-Two Sum
- Trading——Study Notes
- java Clone 中shallow clone 和 deep clone
- WCF System.ServiceModel.AddressAccessDeniedException
- ini文件的操作
- Valid Parentheses
- java的FileChannel使用方法。
- 由浅入深谈流形
- 求N个实数的最大值和最小值