[LeetCode][1]Two Sum解析 -Java实现

来源:互联网 发布:风行直播软件下载 编辑:程序博客网 时间:2024/06/05 20:27

Q:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

A:

以下解法和代码没有借阅以往任何资料,如果有更好的解法请在评论区留言

题目的意思是给一个数组,给一个特殊的数字,返回数组中相加等于目标数字的两个索引,你可以假设每一个特殊数字都是单解。

public class TwoSum {public static int[] twoSum(int[] array,int target){for(int i=0;i<array.length;i++){for(int j = 0;j<array.length-i;j++){if((array[i]+array[j])==target)return new int[]{array[i],array[j]};}}return null;}public static void main(String[] args){int[] array = new int[]{1,2,3,4,5,6,7,8,9};int[] indices = TwoSum.twoSum(array, 5);if(indices!=null){System.out.println(indices[0]+"    "+indices[1]);}}}
这是基础解答,一般人第一反应应该都是这样,这种方法遍历两次代价太高,我们可以具体解析一下看看有没有更加便捷的解决方法。

只要我们取出array中的max和min,去掉array中大于target-min和小于target-max的数值,这样可以缩减范围,生成newarray。

那么接下来我们只需要对有序序列newarray中的头尾相加,如果大于target则把尾值去掉,如果小于target则把头值去掉,这样可以把两次循环O(n^2)化为O(2n)约等于O(n)

但是,这时候我们发现排序算法是O(n^2)的,所以这种解法就无解了。

另一种情况,我们把target的所有情况列出来一共有floor(target/2)种,我们只要维护这样一个数组targetArray[0-target]只要targetArray[i]>=1且targetArray[target-i]>=1即可返回。(假设array中没有负数)

代码如下

public static int[] newTwoSum(int[] array,int target){int[] targetArray = new int[target+1];for(int i :array){if(i>=0&&i<=target){targetArray[i]++;if(targetArray[target-i]>=1){return new int[]{i,target-i};}}}return null;}


1 0