LeetCode 之 two Sum寻找两个相加之和为给定值的两个数
来源:互联网 发布:缺少网络协议 编辑:程序博客网 时间:2024/04/27 17:28
题目
Given an array of integers, find two numbers such thatthey add up to a specific target number.
The function twoSum should return indices of the twonumbers such that they add up to the target, where index1 must be less thanindex2. Please note that your returned answers (both index1 and index2) are notzero-based.
You may assume that each input would have exactly onesolution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
源文档 <https://oj.leetcode.com/problems/two-sum/>
题目意思就是说,输入一个数组和目标数值,要求从数组中找出两个数,它们相加之和等于输入的目标数值。返回这两个数的位置。
解题思路:
一、暴力遍历法
直接一个个去寻找对比,两个循环遍历,时间复杂度是O( N^2 ) ,在leetcode上时间超限了。因此需要另觅他路。
二、双向遍历法
由于两个数相加的和必定是三种结果,要么小于,要么等于,或者大于。因此,如果此数组有序,那么就可以用两个指针,从数组的两个方向同时推进,只需要遍历一次就行,需要N时间,考虑到排序的时间复杂度是O(NLogN),因此最后的时间复杂度就是O(NLogN)。
代码如下:
public static int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; ArrayList<Num> list = new ArrayList<Num>(); int length = numbers.length; for (int i=0;i<length;i++) {list.add(new Num(i+1,numbers[i]));} Collections.sort(list); for (int i = 0,j=length-1; i < length && j>i; ) {int sum = list.get(i).getValue() + list.get(j).getValue();if (sum == target) {result[0] = list.get(j).getIndex();result[1] = list.get(i).getIndex();break;}else if (sum > target) {j--;}else if (sum < target) {i++;}} return result; } private static class Num implements Comparable<Num>{ private int index; private Integer value; public Num(int index,int value){ this.index = index; this.value = value; }public int getIndex() {return index;}public Integer getValue() {return value;}@Overridepublic int compareTo(Num o) {return this.value.compareTo(o.value);} public String toString() {return "value="+value+" ";} }
结果:Accept通过测试。
- LeetCode 之 two Sum寻找两个相加之和为给定值的两个数
- (leetcode)1. 查找数组中两个数之和为给定值Two Sum---Java
- 167 Two Sum II (给定数组求相加为定值的两个数)
- leetcode之深搜递归回溯类-----1/167/653. two sum(记忆化搜索寻找和为给定值的两个数)
- 1048. Find Coins (25) -- 二分法,寻找和为定值的两个数 (Two Sum - leetcode)
- 快速寻找满足条件的两个数(两数之和为给定值)
- leetcode 1: 找出两个数相加等于给定数 two sum
- Two Sum 数组中找两个之和为sum@LeetCode
- Two Sum 从数组中找到两个位置的值相加和为给定目标的值
- Two sum 在数组中寻找和为指定值的两个数
- 1.Two Sum (数组中两个数之和为n)
- LeetCode OJ 之 Two Sum(两个数的和)
- 1. Two Sum 给定一个数组和一个数,输出两个和为给定数的数组元素的下标
- [Leetcode #1]Two Sum 从数组中找出和为特定值的两个数
- 一个无序数组中两个数之和等于给定的值sum
- leetcode Add Two Numbers 两个数相加
- 在给定数组中查找两个数的和为给定值sum
- LeetCode-Two Sum(编程之美-快速寻找满足条件的两个数字)
- 【BNU Summer Training 2014.07.25】 Final Exam Arrangement (贪心)
- A*寻路算法
- java面向对象-自定义异常处理
- HDU 1026 Ignatius and the Princess I
- HDUJ 1272 小希的迷宫 并查集
- LeetCode 之 two Sum寻找两个相加之和为给定值的两个数
- 设计模式之抽象工厂
- java mysql jdbc 最终版
- Java是传值还是传引用
- java面向对象-RuntimeException异常
- 【拯救电源键】最详尽的android开发一键锁屏实例 提供免费源码+apk
- HDU 1015 Safecracker
- [C++面试题]之单链表
- java 泛型详解