Leetcode 之 Two Sum I

来源:互联网 发布:windows定时运行脚本 编辑:程序博客网 时间:2024/06/06 04:17

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

题大概是找到数组中和为target的两个数,开始没看清题目,以为要用到动规,后来发现就是一个简单的二重循环,随便写了写发现时间太久。
16 / 16 test cases passed.
Status: Accepted
Runtime: 476 ms

开始想优化,开始加了if(nums[i] > target)就continue,以为可以过滤掉一部分,结果忽略了有负数存在的情况,果断WA。

后来用哈希表,哈希表是一种重要的存储方式,也是一种常见的检索方法。其基本思想是将关系码的值作为自变量,通过一定的函数关系计算出对应的函数值,把这个数值解释为结点的存储地址,将结点存入计算得到存储地址所对应的存储单元。检索时采用检索关键码的方法。现在哈希表有一套完整的算法来进行插入、删除和解决冲突。在Java中哈希表用于存储对象,实现快速检索,能在O(n)实现元素查找。

于是扩展成哈希表的版本,一边计算一边存储,如果当前哈希表没有要找的数对,就把当前值存进去,否则直接输出就行。上代码:

public int[] twoSum1(int[] nums, int target) {              int[] result = new int[2];        int len = nums.length;        int first = 0, remain = 0;        for(int i = 0;i < len;i++){            first = i;            remain = target - nums[i];            for(int j = i + 1; j < len;j++){                if(nums[j] == remain){                    result[0] = first + 1;                    result[1] = j + 1;                    break;                }            }        }        return result;    }

16 / 16 test cases passed.
Status: Accepted
Runtime: 356 ms

0 0
原创粉丝点击