Leetcode 1:Two Sum

来源:互联网 发布:淘宝怎么做推广 编辑:程序博客网 时间:2024/04/28 08:45

Two Sum

Total Accepted: 141164 Total Submissions: 769155 Difficulty: Medium

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


【算法思路】:不考虑时间复杂度,简单直观的算法通过两层循环,数组的基本操作实现index1从0——>nums.length-1;index2从index1+1——>nums.length-1,保证了index1<index2.时间复杂度O(n*n)

AC的java代码如下:

public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] s = new int[2];        //数组从0开始计数到,nums.length-1        for(int index1 = 0;index1 < nums.length-1;index1++){            for(int index2 = index1 +1;index2 < nums.length;index2++){                if(nums[index1] + nums[index2] == target){                    s[0] = index1 + 1;                    s[1] = index2 + 1;                }            }        }        return s;    }}
Testcase:

nums = [2, 7, 11, 15]
target = 26

显示结果:

Your answer
[3,4]
Expected answer
[3,4]
Runtime: 0 ms

运行过程:index1= 0,nums[index1] = 2,index2 = index1+1,nums[index2] = 7,……找不到nums[0]nums[index2]= 26;index1 +1 =1

          index1= 1,nums[index1] = 7,index2 = index1+1,nums[index2] = 11,……找不到nums[1]+nums[index2]= 26;index1 +1 =2

          index1= 2,nums[index1] = 11,index2 = index1+1,nums[index2] = 15,……找不到nums[2]+nums[3]= 26;index1 += 1;index2 += 1;

最终结果:index1 = 3;index2 = 4.


【算法思路】:

显然,时间复杂度需要再降低才行。看过别人的题解后,使用了Java中的Map,利用HashMap,存储数组中的值和Index,由于HashMap中查询键值对的开销是固定的,因此在性能上可以得到很大的提升。

对输入先构建HashMap,对于HashMap需要考虑,用什么做key,什么做value。题目中要求求两者的和,显然,用数组值做index,来检索index是合理恰当的设置。遍历数组,构建这样的HashMap。

第二遍遍历数组,对每个值value_i,在HashMap中查找是否存在对应的target-value_i的值,若存在,根据这个key找到对应的value值,即得到要找的两个index值。由于数组遍历的顺序是由小到大,因此得到的map中的index2必然大于index1。

考虑用HashMap键值对实现,算法只需要两次循环,map.get(gap)得到一个Object的变量,需要强制类型转换为int类型。算法复杂度降低为O(2*n).


java代码:

public class Solution {    public int[] twoSum(int[] nums, int target) {              int[] s = new int[2];        //用HashMap()键值对实现,        Map map = new HashMap();        for(int i = 0; i < nums.length; i++){            map.put(nums[i], i);        }        //数组从0开始计数到,nums.length-1        for(int i = 0;i < nums.length-1;i++){            int gap= target - nums[i];            //判断存在,并且map.get(gap)>i            if(map.get(gap)!= null && (int)map.get(gap)!= i){                s[0] = i+1;                s[1] = (int)map.get(gap) + 1;//得到内容为gap的下标,即为index                break;        }             }        return s;            }}


0 0