LeetCode 1: Two Sum

来源:互联网 发布:acid3 知乎 编辑:程序博客网 时间:2024/06/12 20:11

题目:

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
题目分析:

给定一个整形的数组,返回数组中两个元素的下标,这两个数的和为给定的值。假设对于每个确定的输入值都只有一种解。

思路:

这个题在LeetCode OJ上给出了三种解决方案:Brute force(简单匹配算法)、Two-pass hash table、 One-pass hash table。后两种笔者不知道怎么翻译了……有时候翻译成中文倒是没有英文那么直观。

对于第一种Brute force,网上有说成是暴力算法的,主要就是遍历,时间复杂度高是O(n^2),空间复杂度是O(1)直接上代码:

public class Solution {    public int[] twoSum(int[] nums, int target) {        int result[] = new int[2];        int i;        int j;        for(i=0;i<nums.length-1;i++) {            for(j=i+1;j<nums.length;j++)                if (nums[i] + nums[j] == target) {                    result[0] = i;                    result[1] = j;                    return result;                }        }        return null;    }}

Two-pass hash table:最主要的思路来源一个问题“对于一个数组来说,维护其字面值和索引的最好的方式是什么?是哈希表。”首先将所有元素存储到哈希表中,遍历nums中的元素,每遍历一个元素时使用target-遍历元素,得到的结果再去哈希表中找,寻找的时间复杂度接近O(1),这样,我们只需要遍历一遍就能找到结果。整个算法的时间复杂度是O(n),空间复杂度是O(n)。算法的核心就是时空转换嘛,上代码:

public class Solution {    public int[] twoSum(int[] nums, int target) {        Map<Integer, Integer> map = new HashMap<>();        for(int i=0;i<nums.length;i++) {            map.put(nums[i],i);        }        for(int i=0;i<nums.length-1;i++) {            int complement = target - nums[i];            if(map.containsKey(complement)&&map.get(complement)!=i) {                return new int[] {i,map.get(complement)};            }        }        return null;    }}

One-pass hash table:我个人觉得这个算法棒极了,和第二种算法的区别在于思路!思路!思路!重要的事情说三遍!在建立哈希表的同时就可以一边看当前哈希表中是否有符合条件的值,如果有,哈希表还没建完就找到了答案,岂不妙哉?虽然时间复杂度和空间复杂度同第二种算法~,话不多说上代码:

public class Solution {    public int[] twoSum(int[] nums, int target) {        Map<Integer, Integer> map = new HashMap<>();        for(int i=0;i<nums.length;i++) {            int complement = target - nums[i];            if(map.containsKey(complement)&&map.get(complement)!=i) {                return new int[] {i,map.get(complement)};            }            map.put(nums[i],i);        }        return null;    }}


0 0
原创粉丝点击