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通过测试。


0 0
原创粉丝点击